Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I target this div using CSS?

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> 
like image 208
J82 Avatar asked Mar 07 '14 01:03

J82


People also ask

How do I target a div class in CSS?

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 (.)

How do I target a specific element in CSS?

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.

Can I use Target in CSS?

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.

How do you target ul li in CSS?

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.


1 Answers

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; } 
like image 54
Josh Crozier Avatar answered Oct 08 '22 09:10

Josh Crozier