Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a display:none property applied to parent element in specific child elements

Tags:

html

css

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)

like image 589
Ash Avatar asked Oct 14 '25 13:10

Ash


2 Answers

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;
}

FIDDLE

like image 125
jmore009 Avatar answered Oct 18 '25 22:10

jmore009


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

like image 39
Ricardo Castañeda Avatar answered Oct 18 '25 23:10

Ricardo Castañeda