Digital Ninja
Digital Ninja

Reputation: 3741

How to use nth-child in CSS to select all elements after a certain one?

I've seen jQuery has a :gt(n) solution, but can the same behavior be achieved in CSS?

What I want is for the mobile website to not have more than 3 elements in some lists. So I would need something along the lines of:

@media(max-width:768px) {
   .list li:gt(3) {
      display:none;
   }
}

And I want to try avoiding using Javascript for it. Since the :gt(n) selector doesn't seem to exist in CSS, can the same selection be achieved with the :nth-child(n) selector?

Upvotes: 39

Views: 42481

Answers (4)

Alessandro Incarnati
Alessandro Incarnati

Reputation: 7246

Yes you can do it using :nth-child(n+4)

In your case:

@media(max-width:768px) {
   .list li:nth-child(n+4) {
      display:none;
   }
}

You can see this fiddle : http://jsfiddle.net/wgLCH/2/

Upvotes: 52

imbondbaby
imbondbaby

Reputation: 6411

Try this:

@media(max-width:768px) {
    .list li:nth-child(n+4) {
      display:none;
   }
}

JSFiddle Example

More info here

Upvotes: 5

Moshtaf
Moshtaf

Reputation: 4903

p:nth-child(n+4)
{
    background:#ff0000;
}

JSFiddle Sample

Upvotes: 0

kazy
kazy

Reputation: 1141

:nth-child(n+3) is the answer.

Upvotes: 0

Related Questions