CSS - greater than selector - select items greater

2019-04-06 15:12发布

问题:

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?

回答1:

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.


回答2:

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

p:nth-of-type(n+3)


回答3:

You can use sibling selector:

p + p + p {display:none;}

Other than the first two, it selects all!

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