Reputation: 7
I would like to change styles for nested divs like in example below:
<div class="box"> #1
<div> #2
<div> #3
<div> #4
<div></div> #5
<div></div> #6
<div></div> #7 **How to style this div when class name is not present?**
</div>
</div>
</div>
</div>
I was able to access div #4 in this way:
.box div div div {}
But what is the way to access div #5 #6 #7?
Upvotes: 0
Views: 2344
Reputation: 7991
You can simply achieve this by following line of css
.box div:nth-child(3) {
border: 1px solid red;
}
<div class="box">
<div>
1
<div>
2
<div>
3
<div> 4</div>
<div> 5</div>
<div> 7</div>
</div>
</div>
</div>
</div>
Upvotes: 0
Reputation:
If those last three div
elements were really intended to have no content, there's a shortcut:
.box div:empty:after { content: 'I am empty'; } /* all of them */
.box div:empty:nth-child(1):after { content: 'Child 1'; } /* specific */
Upvotes: 0
Reputation: 115011
To access #7 you have a two or three options all of which use the direct descendant selector >
to limit the context to children of the #4 div.
.box div div div > div:last-of-type{}
/* assumes there are no additional divs after #7 */
or
.box div div div> div:last-child {}
/* assumes that the div is, in fact, the last child
or even
.box div div div> div:nth-child(3) {}
/* assumes that the 3rd child is a div */
Upvotes: 4
Reputation: 207901
With plain CSS you can use the pseudo-class :last-child
div.box > div > div > div > div:last-child {
color:red;
}
<div class="box">
<div>
<div>
<div>
<div>5</div>
<div>6</div>
<div>7</div>
</div>
</div>
</div>
</div>
Upvotes: 2