Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally set style if sibling element exists in PURE CSS [duplicate]

Tags:

html

css

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!

like image 826
user1876246 Avatar asked Mar 08 '17 20:03

user1876246


People also ask

How do I select a sibling element in CSS?

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 .

How do I apply CSS to child element based on parent?

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.

How do I select a second sibling in CSS?

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.

What is a sibling element in CSS?

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.


1 Answers

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>
like image 119
Michael Coker Avatar answered Sep 25 '22 01:09

Michael Coker