So I have this query to get the last-child
when there are 7 or more elements
li:nth-last-child(7) ~ li:last-child {
background: red;
}
This works for any number of elements as long as there is a minimum of 7
. What I want to do is the opposite, get the first-child
.
I tried the following
li:nth-last-child(7) ~ li:first-child {
background: red;
}
But that does not work. Strangely I can get the second child element using the following
li:nth-last-child(7) ~ li:nth-child(2) {
background: red;
}
I know this is pretty complex CSS, and may not even be possible, but I am wondering if it can be done. I'd rather not use JS if at all possible. I guess treat this as a challenge ;)
The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
Syntax. The nth-last-child pseudo-class is specified with a single argument, which represents the pattern for matching elements, counting from the end. :nth-last-child( <nth> [ of <complex-selector-list> ]? )
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
Yes, it's possible. We can check with CSS @supports rule like the following.
You can select the first element when there are 7 or more elements by using the below selector:
div:first-child:nth-last-child(n+7) {
color: red;
}
Explanation:
nth-last-child(n+7)
- Will select all but the last seven child elements. When there are less than seven children, this will match none. :first-child:nth-last-child(n+7)
- Will select only the element which is also the first child among the elements which match the other part (which is, select only first child when there are seven or more children).container > div:first-child:nth-last-child(n+7) {
color: red;
}
<h3>Has seven children</h3>
<div class='container'>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
</div>
<h3>Has six children</h3>
<div class='container'>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
</div>
<h3>Has nine children</h3>
<div class='container'>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
</div>
Fiddle Demo (For some reason it is not working with n+7
in snippet)
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