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?
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.
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.
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 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.
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/
Try this:
@media(max-width:768px) {
.list li:nth-child(n+4) {
display:none;
}
}
JSFiddle Example
More info here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With