CSS - more than a selector - select elements more than N

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

 <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 a Chrome web browser.

How do I fix my code to achieve the goal I originally stated?

+8
html css css-selectors
source share
3 answers

If they are brothers and sisters, the simplest approach with some backward compatibility:

 p + p ~ p { display: none; } 

JS Fiddle demo .

You can also use:

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

JS Fiddle demo .

Literature:

+18
source share

: gt is just a jQuery shortcut to select it in css:

 p:nth-of-type(n+3) 
+5
source share

You can use the sibling selector:

 p + p + p {display:none;} 

In addition to the first two, he chooses everything!

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

+3
source share

All Articles