-1

I have HTML like this:

<div class="parent">
    <div class="thumb">...</div>
    <div class="text">...</div>
</div>

I want the background of the "text" div to be white. But ONLY if there is no "thumb" div preceding it since that div won't always be there.

I realize I can do something like this:

.parent .text {background-color: #fff;}
.parent .thumb + .text {background-color: transparent;}

So color ALL the text backgrounds white and then override the ones that have the thumb div preceding it.

But I was wondering if it's possible to do something like:

.parent :not(.thumb +) .text {background-color: white;}

To kill two birds with one stone by only targeting the "text" div when there is no preceding "thumb" div. Any ideas?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Rothgarr
  • 173
  • 1
  • 8

2 Answers2

0

You can use conditionals (if/else) in CSS using SASS:

$type: monster;
p {
  @if $type == ocean {
    color: blue;
  } @else if $type == matador {
    color: red;
  } @else if $type == monster {
    color: green;
  } @else {
    color: black;
  }
}

Check documentation!

Or, you can use JavaScript/jQuery to add/remove classes according to whatever condition you need.

There is no actual if/else for standard CSS.

SrAxi
  • 19,787
  • 11
  • 46
  • 65
-1

The way you mention is already the way to target it only when there's no preceding div; .thumb + .text {} styles only apply when there is a .thumb element immediately preceding a .text element:

.parent {
    background: grey;
    border: 1px solid red;
    margin-bottom: 30px;
}

.text {
    background: purple;
}

.thumb + .text {
    background: white;
}
<div class="parent">
    <div class="thumb">...</div>
    <div class="text">White bg</div>
</div>

<div class="parent">
    <div class="text">White bg</div>
</div>
TylerH
  • 20,799
  • 66
  • 75
  • 101