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>
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)
URLs with an # followed by an anchor name link to a certain element within a document. The element being linked to is the target element. The :target selector can be used to style the current active target element.
The target selector is used to represent a unique element (the target element) with an id matching the URL's fragment. It can be used to style the current active target element. URLs with a # followed by an anchor name link to a certain element within a document.
first thing is you should remove the . sign from the ul in your css. we use . signt to define a class and # sign to define an id.
In this particular instance, you could use the adjacent sibling combinator, +
.
EXAMPLE HERE
.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.
EXAMPLE HERE
.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.
EXAMPLE HERE
.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:
EAXMPLE HERE
.b ~ .b { width:200px; background:blue; color:#fff; } .b ~ .b ~ .b { width:auto; background:transparent; color:#000; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With