I have the following structure, where second element may or may not appear.
<div class="wrapper">
<div class="firstElement"></div>
<div class="secondElement"></div>
</div>
I want to conditionally set styles on .firstElement
ONLY if .secondElement
exists.
Is there a way to do this with PURE CSS? With either sibling selectors/ parent selectors?
Thanks!
The adjacent sibling combinator ( + ) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element .
It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinator ( > ), which is placed between two CSS selectors. For example, div > p selects all <p> elements where the parent is a <div> element.
Selecting Only the Next Sibling with Adjacent Sibling Combinator ( + ) The + character used in CSS is a combinator — it combines 2 CSS selectors. It selects the second element, only if it is just after the first element, and both elements are children of the same parent.
The general sibling combinator ( ~ ) separates two selectors and matches all iterations of the second element, that are following the first element (though not necessarily immediately), and are children of the same parent element.
In general, no. CSS reads forwards/down the DOM - it won't read backwards/up. But with this markup, you could use :not(:last-child)
.firstElement:not(:last-child) {
color: red
}
<div class="wrapper">
<div class="firstElement">target this</div>
<div class="secondElement"></div>
</div>
<div class="wrapper">
<div class="firstElement">not this</div>
</div>
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