8

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!

user1876246
  • 1,219
  • 5
  • 18
  • 33

1 Answers1

19

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>
Michael Coker
  • 52,626
  • 5
  • 64
  • 64