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?
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.
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.
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.
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.
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:
:nth-of-type()
pseudo-class.+
) combinators.~
) combinators.:gt is just a jQuery short hand, to select it in css:
p:nth-of-type(n+3)
You can use sibling selector:
p + p + p {display:none;}
Other than the first two, it selects all!
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