12

I have the following structure:

<ul id="test">
    <li class="myclass">Item1</li>
    <li class="myclass">Item2</li>
    <li class="myclass">Item3</li>
    <li class="myclass">Item4</li>
    <li class="myclass">Item5</li>
</ul>

I want to hide the first three items. I wrote the following code but it only hides the first child and not the next two.

#test li:first-child
{
    display:none;
}

How do I hide the other two also?

3 Answers 3

16

You can use the nth-child selector:

#test li:nth-child(-n+3) {
    display: none;
}

From the linked MDN doc:

Matches if the element is one of the first three children of its parent

0
4
#test li:nth-of-type(1),
#test li:nth-of-type(2),
#test li:nth-of-type(3) {
  display:none;
}
0
2

Use CSS3:

#test li:nth-child(-n+4)
{
display:none;
}

Keep in mind that this property is supported in all major browsers, except IE8 and earlier.

Not the answer you're looking for? Browse other questions tagged or ask your own question.