0

Is there a way to style a parent element if the child element is empty? For example:

Here, the <li> element is empty so I'd like the ul element to be styled with padding: 20px:

<ul class="list">
    <li></li>
</ul>
henrywright
  • 10,070
  • 23
  • 89
  • 150
  • 10
    a) there's no parent selector in CSS and b) CSS can't read the content of your elements. So no, you'd need JavaScript. – j08691 May 19 '14 at 16:08
  • @henrywright - you'd only be able to check if the `li` contained no child elements: https://developer.mozilla.org/en-US/docs/Web/CSS/:empty – Joe May 19 '14 at 16:09
  • Close voter please tell me where in my question it is unclear what I'm asking – henrywright May 19 '14 at 16:51
  • ah it's unclear about the `
  • ` You don't even say if your `ul` has only 1 `li` or it has some `li`s? if it has some `li`s so which `li` is empty to be the condition to style your `ul` or any `li`?
  • – King King May 19 '14 at 16:53
  • @KingKing thanks for your comment. There is a single `
  • ` element.
  • – henrywright May 19 '14 at 16:56
  • if there is only 1 `li`, you may have a workaround such as instead of setting the padding of your `ul`, why not setting the `margin` of your `li`? that way you can use the `:empty` selector like this `li:empty { margin:20px;}`. Of course traversing back to your `ul` to set its `padding` to `20px` is impossible in CSS3 (maybe it's possible in CSS4). – King King May 19 '14 at 16:58
  • @KingKing true about the workaround. But I've opted for a jQuery solution (see the accepted answer) because this will cover future situations where there may be more than a single `li` – henrywright May 19 '14 at 19:07
  • Does this answer your question? [Is there a CSS parent selector?](/q/1014861/90527) – outis Aug 06 '22 at 22:50