Reputation: 576
I want to add the margin-top
style to .three
, but only if .one
has a .two
.
.one {
background: indianred;
height: 100px;
width: 100px;
}
.three {
background: bisque;
height: 100px;
width: 100px;
}
.one .two + .three {
margin-top: 20px;
}
<div class="one">
<div class="two">hello</div>
</div>
<div class="three">there</div>
<div class="one">
</div>
<div class="three">there</div>
Can this be done? Appreciate the help.
Upvotes: 1
Views: 467
Reputation: 2260
As far as I know, the closest you can currently get is reversing the logic and using :empty
. It's a poor substitute and probably won't work for your needs, but it can work - under the right circumstances.
.one {
background: indianred;
height: 100px;
width: 100px;
}
.three {
background: bisque;
height: 100px;
width: 100px;
margin-top: 20px;
}
.one:empty + .three {
margin-top: 0;
}
<div class="one">
<div class="two">hello</div>
</div>
<div class="three">there</div>
<div class="one"></div><!-- Note how .one is completely empty with not even a newline -->
<div class="three">there</div>
This is sort of cheating though, as it's not checking to see if .one
has .two
. Instead it's assuming that .one
does have a child and that child is .two
. If .one
doesn't have a child, then no margin is applied. This is making a lot of assumptions and is useless most of the time, unless you can make those same assumptions.
The only way you could use this is if you know that .two
is the only possible child and that if .one
doesn't have .two
then it will always have nothing. No spaces, newlines, or anything else that can be counted as a child (comments are safe).
A good way to see if you can use this (or something similar) is to try to rewrite your logic. If 'Add margin-top to .three
, but only if .one
has a .two
' can be rewritten as 'Remove margin-top from .three
, but only if .one
is empty' then this method will work. Depending on what you actually need, there may be other ways to rethink your logic into something currently doable.
Upvotes: 2