Is it possible to display only the first, second and last children using nth-child?
What will be the algebraic expression?
I'm not able to figure this out, even after using CSS selectors.
The :nth-last-child(n) selector matches every element that is the nth child, regardless of type, of its parent, counting from the last child.
Definition and UsageThe :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.
The CSS child selector has two selectors separated by a > symbol. The first selector indicates the parent element. The second selector indicates the child element CSS will style.
You can do something like this with multiple :not
pseudo-class
ul li:not(:nth-child(1)):not(:nth-child(2)):not(:last-child) {
display: none;
}
<ul>
<li>First</li>
<li>Second</li>
<li>random</li>
<li>random</li>
<li>random</li>
<li>Last</li>
</ul>
Show your items only when either of the following applies :
:nth-child(-n+2)
(first + second item):last-child
(last item)li {
display: none;
}
li:nth-child(-n+2), li:last-child {
display: list-item;
}
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>
Not sure about a single algebraic expression, but you can group selectors into a single rule.
li { display: none; }
li:first-child,
li:nth-child(2),
li:last-child {
display: list-item;
}
<ul>
<li>First</li>
<li>Second</li>
<li>random</li>
<li>random</li>
<li>random</li>
<li>Last</li>
</ul>
OR
li { display: none; }
li:nth-child(-1n + 2),
li:last-child {
display: list-item;
}
<ul>
<li>First</li>
<li>Second</li>
<li>random</li>
<li>random</li>
<li>random</li>
<li>Last</li>
</ul>
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