0

Is it possible to apply style to a parent element if child is not empty? I need to remove border from empty container.

.parent {
  border: 1px solid #ccc;
  padding: 10px;
  margin: 20px;
}
<div class="parent">
  <div class="child">
    not empty
  </div>
</div>

<div class="parent">
  <div class="child">
  </div>
</div>

I've tried:

.parent:not(> .child:empty)

but cleaerly this is going to look for .child class inside .parent... Is there a way to do it with CSS?

santa
  • 13,148
  • 42
  • 144
  • 230

4 Answers4

0

The title seems to be a tad misleading, but if want to apply css styling to a div that does not contain any contents you may run into some problems, what may work is defining a label inside the child div and setting its color to match your background.

<label style="color= "white"> a </label>

this will provide the intended look

0

After a bit of research, it would appear the best option would be the pseudo-class selector :has().

Unfortunately, it's experimental (it's still a draft) and can only be used with functions like document.querySelector() and not directly on stylesheets.

Research info and credits:

Juan Marco
  • 1,806
  • 2
  • 18
  • 22
0

You might want to approach this from the reverse train of thought. Instead of IF it isn't empty. Style your element how you want to originally, then style the ones that are empty differently.

.child {
   border:1px solid #000;
}
.parent .child:empty {
   border:none;
}

JS fiddle for reference: https://jsfiddle.net/Le93svqb/

This would allow you to set your default style on all the .child elements and style the empty ones in another manner.

-1

i think it will be easier for you if you use some JavaScript