Previous Sibling Selector in CSS

Previous Sibling Selector in CSS

Sorry, no previous sibling selector exists in CSS; so in pure CSS you can't target the sibling before an empty element - or can you?

Rearrange the display order using flexbox and the order property and then use the next-sibling selector. Technically a work-around but it recently made my life easier.

Start out with a few flexbox children in a row. Imagine the first has text, the second is a dash and the third has text. You want the second to show only when the third has text; something like this:

[Some Text][ - ][Other Text]
// or ....
[Some Text][   ][   ]

The HTML you'd be working with, may look a bit like this:

<div id='parent'>
  <div>First Text</div>
  <div> - </div>
  <div>{{ secondText }}</div>
</div>

CSS as-is won't allow you to say "show my 2nd item if my 3rd isn't empty" – but here's the magic:

.parent {
  display : flex
  flex-direction: row
}
.parent > div:nth-child(3) {
  order : 2
}
.parent > div:nth-child(2):empty + div {
  display: none
}

and then modify the HTML ...

<div id='parent'>
  <div>First Text</div>
  <div>{{ secondText }}</div>
  <div> - </div>
</div>

Notice how the order of the child div tags is changed - but the rule with the order keyword makes them display the same.

Since the source order is what matters, you can now target the "2nd" element if the "3rd" is empty via .parent > div:nth-child(2):empty + div