0

imagine a html code which I cannot change. something like:

    <div class="a">
        <div class="aa">
            <div class="aa1">
    
            </div>
            <div class="aa1">
    
            </div>
            <div class="aa1">
    
            </div>
            <div class="aa1">
    
            </div>      
        </div>
        <div class="b">
            <div class="bb">
                ...
            </div>
        </div>...
    
    </div>

so what I want to change is in 'aa1' s and each one should have different styling.

so in css I could write

    .a .aa .aa1:first-child{
        styling1:;
    }
     .a .aa .aa1:nth-child(2){
        styling2:;
    }
     .a .aa .aa1:nth-child(3){
        styling3:;
    }
     .a .aa .aa1:nth-child(4){
        styling4:;
    }
     .a .aa .aa1:nth-child(5){
        styling5:;
    }

but there is lot of those 'aa1' parts. Is there a way to simplify this where I only have to specify nth-child(x) for each element?

something like:

    .a .aa .aa1
    {
        :first-child{
            styling1:;
        }
        :nth-child(2){
            styling2:;
        }
        :nth-child(3){
            styling3:;
        }
        :nth-child(4){
            styling4:;
        }
        :nth-child(5){
            styling5:;
        }
    }
DarkZeus
  • 61
  • 8

2 Answers2

1

With the current CSS (2.1) version, nesting selectors isn't possible.

You'll have to use something called a CSS preprocessor which does several things, including allowing nested selectors.

I'd recommend SASS (SCSS), and another out there is LESS. You'll need some extra things setup on your PC/Mac for automatically converting preprocessor files to regular CSS files - plenty of other questions and research points on that out there.

If you use SCSS, you can check out what its like on SassMeister so you can see what the nested selectors will look like compiled.

Chris Heath
  • 432
  • 1
  • 11
  • 22
0

one possible solution would be to use the adjacent sibling selector (+) for each "aa1" class and + one for each new style

for example:

.a .aa .aa1 p {
 color: black;
}

.a .aa .aa1 +.aa1 p {
    color: red;
}

.a .aa .aa1 + .aa1 + .aa1 p {
    color: blue;
}

.a .aa .aa1 + .aa1 + .aa1 +.aa1 p {
    color: green;
}
<div class="a">
    <div class="aa">
        <div class="aa1">
            <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p>
        </div>
        <div class="aa1">
            <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p>
        </div>
        <div class="aa1">
            <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p>
        </div>
        <div class="aa1">
            <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p>
        </div>      
    </div> 
</div>