I have an element with children and some of those children themselves have children, some of which use a shared CSS class.
What I'm wanting to do is select the last child of the main element and not also the last sub-child.
I have tried in 2 ways I know thus far:
last-child
.some-class:last-child {
background: lightblue;
}
<div >
<div >one</div>
<div>
<div >sub-one</div>
<div >sub-two</div>
</div>
<div >two</div>
</div>
Last-of-type
.some-class:last-of-type {
background: lightblue;
}
<div >
<div >one</div>
<div>
<div >sub-one</div>
<div >sub-two</div>
</div>
<div >two</div>
</div>
You will see that both of these have two
and sub-two
to be highlighted in blue... I simply only want two
to be highlighted.
CodePudding user response:
You can target the last element of .some-class
directly after .container
.container > .some-class:last-child {
background: lightblue;
}
<div >
<div >one</div>
<div>
<div >sub-one</div>
<div >sub-two</div>
</div>
<div >two</div>
</div>
CodePudding user response:
Use a child >
combinator:
.container>.some-class:last-child {
background: lightblue;
}
<div >
<div >one</div>
<div>
<div >sub-one</div>
<div >sub-two</div>
</div>
<div >two</div>
</div>
Please note that there is no last-of-class
selector in CSS. The selector in the snippet above does the following:
.container>.some-class:last-child
- It selects all elements that are the last child of their parent.
- Then it removes elements that don't have a CSS class
some-class
. - It then removes all elements that are not children of elements with a CSS class
container
.
Your CSS declarations are then applied to the elements remaining.