Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use nth-child in CSS to select all elements after the 3rd one?

Tags:

css

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?

like image 739
Digital Ninja Avatar asked Jul 28 '14 23:07

Digital Ninja


People also ask

How do I select all nth child in CSS?

The :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 you select all third items in CSS?

In addition to the value n being able to be any number, you can also use a formula. nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one.

How do you select all elements except the last one?

It's quite easy to do this using the :not and :last-child pseudo-classes. The :not pseudo-class specifies elements that do not match a list of selectors and the :last-child selects the element if it is the last child among the other elements.

How do I select all child elements except one in CSS?

How to select all children of an element except the last child using CSS? When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.


2 Answers

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/

like image 69
Alessandro Incarnati Avatar answered Sep 28 '22 19:09

Alessandro Incarnati


Try this:

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

JSFiddle Example

More info here

like image 44
imbondbaby Avatar answered Sep 28 '22 18:09

imbondbaby