Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply css to outer div if ul item contains li items

I have two cases in my rendered HTML page.

Case 1:

<ul>
  <li>A</li>
  <li>B</li>
</ul> 
<div class="test">Testing here</div>

Case 2:

<ul></ul>
<div class="test"></div>

In case 1, I want to apply CSS to the div if ul element contains li elements). I don't want anything for case 2. I want a pure CSS approach without any jQuery/JavaScript.

like image 280
Abhi Avatar asked Nov 27 '25 05:11

Abhi


2 Answers

The intended behaviour can be achieved with the use of the Adjacent sibling combinator (+) and the :emptyref pseudo-class, e.g:

ul:empty + .test

Code Snippet Demonstration:

* {
  box-sizing: border-box;
}

ul:empty + .test {
  background: black;
  color: white;
  padding: 5px;
}
<ul>
  <li>A</li>
  <li>B</li>
</ul> 
<div class="test">Testing here</div>

<ul></ul>
<div class="test">Testing here</div>
  1. 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. ref

  2. The :empty CSS pseudo-class represents any element that has no children. Children can be either element nodes or text (including whitespace). Comments or processing instructions do not affect whether an element is considered empty or not. ref

like image 182
UncaughtTypeError Avatar answered Nov 28 '25 19:11

UncaughtTypeError


In addition to UncaughtTypeError's answer.

There is a selector :not(:empty) for applying css to element if it has a child.

Check the :not(:empty) for more details about the selector.

* {
  box-sizing: border-box;
}
ul:not(:empty) + .test {
  background: black;
  color: white;
  padding: 5px;
}
<ul>
  <li>A</li>
  <li>B</li>
</ul> 
<div class="test">Testing here</div>

<ul></ul>
<div class="test">Testing here</div>
like image 30
Noopur Dabhi Avatar answered Nov 28 '25 20:11

Noopur Dabhi