Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 645
Mithil Bhoras Avatar asked Apr 03 '16 17:04

Mithil Bhoras


People also ask

Which nth child () selector will target only the last list item?

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.

How do you use the nth of a 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.

How do I select first and second child in CSS?

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.


3 Answers

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>
like image 129
Nenad Vracar Avatar answered Nov 09 '22 23:11

Nenad Vracar


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>
like image 20
John Slegers Avatar answered Nov 10 '22 00:11

John Slegers


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>
like image 25
Michael Benjamin Avatar answered Nov 10 '22 00:11

Michael Benjamin