Show The First N Items In A List With CSS

A common design method is to use list elements to create the layout of a menu or a section on a page. This is all fine until the users come along and create lots of list items that mess up the layout of the page. In CSS it is possible to show only the first few items in the list so that your users can't mess up the layout.

To show only the first 2 items in a list use the adjacent sibling combinator to hide the third element and everything after that.

li + li + li {display: none;}

You can add as many li items to this list as you need to to ensure that the layout of your page works with the correct number of elements.

You can also do the same thing in CSS3 using a default display:none on all list items and then just showing the first 2 items in the list using the :nth-child pseudo-class.

li {
  display: none;
}
li:nth-child(-n+2){
  display: list-item;
}

This will set the list item back to it's default of 'list-item', but you can set it to 'block' if you are using the list items as blocks of content. Be careful with the above styles as they will effect all list elements in your page. You'll need to surround these selectors with a ul or ol element and a class so that you are only targeting the list you want to target.

This is a neat (and devious) way of preventing additional main menu items from breaking the layout. If you are interested in seeing it at work then I created a codepen to show it in action.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
14 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.