Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the first 3 list items and hide the rest with CSS nth-child?

Is it possible to select multiple children past a defined number with CSS selectors?

I'd like to hide all list items past #3:

<ul>   <li>1</li>   <li>2</li>   <li>3</li>   <li>4</li> <!-- hide this -->   <li>5</li> <!-- hide this --> </ul>  <style>   ul li:nth-child(X) {     display: none;   } </style>
like image 532
Yahreen Avatar asked Aug 07 '12 17:08

Yahreen


People also ask

How do I hide the nth child in CSS?

jQuery selector is described in the Selectors/nthChild docs, and the above can be accomplished with $("li. mybutton:nth-child(2)"). hide() .

How do I select a specific Nth child in CSS?

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 all 3 children in CSS?

formula (an + b)nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one. Multiplication and division are not supported in nth-child(n) formulas.

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.


1 Answers

I do not know which browser supports this, but you can pass a formula to :nth-of-type():

ul li:nth-of-type(1n+4) {display: none;} /* should match your case */ 

Further details on: http://www.w3schools.com/cssref/sel_nth-of-type.asp

Edit

I altered it from (n+4) to (1n+4) since the first version works but isn't valid. I use this in media queries to hide cut-down items on smaller screens.


Example:

b:nth-of-type(1n+4){ opacity:.3; }
<b>1</b>  <b>2</b>  <b>3</b>  <b>4</b>  <b>5</b>
like image 111
DerWaldschrat Avatar answered Sep 23 '22 18:09

DerWaldschrat