Reputation: 169
Ive been scratching my head over this one for a while and cant figure out why its not working. Im basically trying to hide some specific content on a page using only CSS - for this bit of work i wont have access to the on page HTML but will be able to inject CSS at will.
Okay so ive got a basic HTML structure as follows:
<div id="content-body">
<p> want this to stay </p>
<h2>want this to stay</h2>
<p> want this to stay </p>
<p> want this to stay </p>
<p> want this removed </p>
<h2>want this removed</h2>
<p> want this removed </p>
<p> want this removed </p>
</div>
Ive put together the following CSS to remove the entire "content-body" element and then override this on specific children, however it doesnt seem to work.
#content-body {display:none}
p:nth-child(1) {display:block !important}
h2:nth-child(2) {display:block}
p:nth-child(3) {display:block}
p:nth-child(4) {display:block}
the important tag doesn't seem to make any difference. Is there anything incorrect about how i've formatted this? (the actual page has a lot more HTML than the example so removing everything through CSS is a lot easier than individually selecting elements, although i may need to do this instead)
Upvotes: 4
Views: 20026
Reputation: 12923
You're hiding the parent element by calling:
#content-body {display:none}
So all of the children will be hidden as well regardless of how you target them. What you need to do instead is hide the p
and h2
elements within #content-body
and then overwrite the ones you want to show by using nth-of-type
instead of nth-child
(since you want to target the 1st h2
and the 3rd p
, etc.) like so:
#content-body p, #content-body h2 {
display: none;
}
#content-body p:nth-of-type(1),
#content-body p:nth-of-type(2),
#content-body p:nth-of-type(3),
#content-body h2:nth-of-type(1) {
display: block;
}
Upvotes: 3
Reputation: 21685
Your first selector #content-body { display: none; }
is hiding everything as it is the container. First hide all of the elements individually by targeting p
and h2
then selectively show elements with nth-of-type selector.
#content-body p,
#content-body h2 { display: none }
#content-body p:nth-of-type(1) { display: block }
#content-body h2:nth-of-type(1) { display:block }
#content-body p:nth-of-type(2) { display:block }
#content-body p:nth-of-type(3) { display:block }
<div id="content-body">
<p>want this to stay</p>
<h2>want this to stay</h2>
<p>want this to stay</p>
<p>want this to stay</p>
<p>want this removed</p>
<h2>want this removed</h2>
<p>want this removed</p>
<p>want this removed</p>
</div>
Upvotes: 0
Reputation: 5812
You can select all direct children with global selector, then you can override that:
#content-body > * { display: none }
#content-body p:nth-child(1),
#content-body h2:nth-child(2),
#content-body p:nth-child(3),
#content-body p:nth-child(4) { display: block }
Example here: jsfiddle
Upvotes: 2