Mithil Bhoras
Mithil Bhoras

Reputation: 339

Display only first, second and last children using nth-child?

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

Answers (3)

Michael Benjamin
Michael Benjamin

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

John Slegers
John Slegers

Reputation: 47111

Show your items only when either of the following applies :

  • :nth-child(-n+2) (first + second item)
  • :last-child (last item)

Demo

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

Nenad Vracar
Nenad Vracar

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

Related Questions