49

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>
Cray
  • 2,774
  • 7
  • 22
  • 32
Yahreen
  • 1,639
  • 7
  • 24
  • 38

1 Answers1

94

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>
vsync
  • 118,978
  • 58
  • 307
  • 400
DerWaldschrat
  • 1,865
  • 13
  • 13
  • Why `:nth-of-type()` and not `:nth-child()`? They both accept formulas, they both can be used interchangeably with `li` (assuming valid markup), and browser support is exactly the same. – BoltClock Aug 07 '12 at 17:58
  • @BoltClock So are you suggesting using `:nth-child()` instead? If so, what would the correct way to do it be? – Yahreen Aug 07 '12 at 18:01
  • @Yahreen: Either way is fine. I just found it odd that you asked about `:nth-child()` but he's going off on a tangent and suggesting `:nth-of-type()` instead. – BoltClock Aug 07 '12 at 18:01
  • @BoltClock His/her solution for `:nth-of-type()` works in my code but I can not get `:nth-child()` to work. If both are equal as far as browser compatibility, I suppose it does not make a difference? – Yahreen Aug 07 '12 at 18:03
  • @Yahreen: Well, both selectors accept the same formula, and it should not make any difference for `li` elements (there is a subtle difference between the two but it is irrelevant). Can we see a demo where your `:nth-child()` isn't working? – BoltClock Aug 07 '12 at 18:08
  • ok, I see, for
  • s they are fully equivalent, I misinterpreted :nth-child(), that is why I was suggesting :nth-of-type()
  • – DerWaldschrat Aug 07 '12 at 18:25
  • This is incredible. CSS still amazes me from time to time. – Rahul Jul 07 '17 at 08:12