Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - greater than selector - select items greater than N

I have several <p> elements in my HTML body. I only want to show the first two paragraphs, and set display:none to all paragraphs after. Why does the following code not work?

<html>

<head>
    <style type="text/css">
        p:gt(2) { display:none; }
    </style>
</head>
<body>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
</body> 

</html> 

My code still shows all 4 paragraph elements in Chrome web browser.

How do I correct my code to achieve the objective I originally stated?

like image 309
John Avatar asked Sep 23 '12 16:09

John


People also ask

What does >>> mean in CSS?

The greater than sign (>) selector in CSS is used to select the element with a specific parent. It is called as element > element selector. It is also known as the child combinator selector which means that it selects only those elements which are direct children of a parent.

How do I choose a multiple nth child?

Definition and Usage 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.

What gives the highest precedence to a CSS selector?

The more specific the CSS selector is, the higher is the precedence of the CSS property declarations inside the CSS rule owning the selector. In general terms, the more specifically (uniquely) a CSS selector targets an HTML element, the higher is its specificity.

How the CSS selector selects the elements that are checked?

The checked selector is used to select all checked elements in input tag and radio buttons. This selector is used with radio buttons, checkbox and option elements.


Video Answer


3 Answers

If they're siblings the easiest approach with some backwards compatibility would be:

p + p ~ p {
    display: none;
}

JS Fiddle demo.

You could also use:

p:nth-of-type(2) ~ p {
    display: none;
}

JS Fiddle demo.

References:

  • CSS Selectors.
  • CSS :nth-of-type() pseudo-class.
  • Adjacent sibling (+) combinators.
  • General sibling (~) combinators.
like image 197
David Thomas Avatar answered Oct 22 '22 12:10

David Thomas


:gt is just a jQuery short hand, to select it in css:

p:nth-of-type(n+3)
like image 26
Armel Larcier Avatar answered Oct 22 '22 13:10

Armel Larcier


You can use sibling selector:

p + p + p {display:none;}

Other than the first two, it selects all!

jsFiddle: http://jsfiddle.net/KK3mk/

like image 25
Praveen Kumar Purushothaman Avatar answered Oct 22 '22 12:10

Praveen Kumar Purushothaman