Reputation: 339
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.
Upvotes: 6
Views: 2890
Reputation: 372274
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>
Upvotes: 2
Reputation: 47111
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>
Upvotes: 2
Reputation: 122155
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>
Upvotes: 10