Reputation: 8457
In the code below, how would I target the second div.b
using CSS?
<div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="b"></div>
<div class="b"></div>
<div class="a"></div>
</div>
Upvotes: 28
Views: 1420
Reputation: 240928
In this particular instance, you could use the adjacent sibling combinator, +
.
.b + .b {
color:red;
}
The above assumes there are no more than two, adjacent .b
elements. If this wasn't the case, the general sibling combinator, ~
, would be more useful assuming there are still only two .b
elements.
.b ~ .b {
color:red;
}
As an alternative, you could also use the following, which will work with multiple .b
elements, regardless of position. Initially, use .b ~ .b
to set the styling of the second, targeted element. You would then need to use .b ~ .b ~ .b
to reset the styling of the .b
elements following the second .b
element.
.b ~ .b {
color:red;
}
.b ~ .b ~ .b {
color:initial;
}
This should theoretically work in all instances, for example:
<div class="a">1a</div>
<div class="a">2a</div>
<div class="a">3a</div>
<div class="b">1b</div>
<div class="a">4a</div>
<div class="b">2b</div> <!-- This would be styled red.. -->
<div class="b">3b</div>
It's also worth noting that the value initial
isn't supported in IE. You could therefore use color:#000
to reset the color back to the defaults. Alternatively, inherit
would work too.
As a more practical example, you could use something like this:
.b ~ .b {
width:200px;
background:blue;
color:#fff;
}
.b ~ .b ~ .b {
width:auto;
background:transparent;
color:#000;
}
Upvotes: 34
Reputation: 178
There is also another way of achieving what you want to do.
div > :nth-child(5){
}
Upvotes: 14