Reputation: 659
I want to style a div only if a certain other div exists inside the parent. Just look at the following piece of code. The parent div is 'main'
, and inside this parent div there are two child divs, that is "first"
and "second"
. I want to style the div "second"
only if the div "first"
exists inside the parent div, that is "main"
. It is possible that sometimes the "first"
div is not inside the main div. Is it possible to do this with CSS?
Millions of thanks in advance.
<div id="main">
<div id="first"></div>
...some other divs...
<div id="second"></div>
</div>
Upvotes: 0
Views: 1323
Reputation: 14800
What you want is to style #second
if it is a sibling of #first
+
is the adjacent sibling selector,
~
is the general sibling selector.
Since you want to allow other divs in between — "...some other divs..." — you'll want the general sibling selector ~
not the adjacent sibling selector +
.
#main #first ~ #second {
color: red;
}
<div id="main">
<div id="first">First (default black color)</div>
<div>some</div>
<div>other</div>
<div>divs</div>
<div id="second">Second (red)</div>
</div>
...and here's an example where #first
doesn't appear
#main #first ~ #second {
color: red;
}
<div id="main">
<div id="not-first">First (default black color)</div>
<div>some</div>
<div>other</div>
<div>divs</div>
<div id="second">Second (red)</div>
</div>
CSS-Tricks has a good article about Child and Sibling Selectors
Upvotes: 2