Can CSS class change based on whether specific child is or is not present?

Viewed 65

I have a div with class "thumbnail". It will always have a child div of class "image1" but may or may not have a child div of class "text".

Is there any way for the parent class to change based on whether there is no div.text or if it only has div.image1? In my case I would like to make the div.thumbnail have a black background (see div.thumbnail:doesNotHave(div.text) in CSS below). Ultimately, I want to do more complex things here but simplified here for this question.

I know that I can make a div.thumbnail.single as with the example but was looking to see if there is a way for this to be detected in CSS without the subclass.

div.thumbnail
{
    background-color: green;
    padding : 1em;
}

div.thumbnail.single
{
    background-color: blue;
}

/* ??? something that does this */
div.thumbnail:doesNotHave(div.text)
{
    background-color: black;
}

div.thumbnail div.image1
{
    background-color : cyan;
}

div.thumbnail div.text
{
    background-color : orange;
}

div.thumbnail div.text span.title
{
    background-color : red;
}
<h2>Image and Text</h2>

<div class="thumbnail">
    <div class="image1">
        image 1
    </div>
    <div class="text">
        text
    </div>
</div>

<h2>Image Only (Single)</h2>

<div class="thumbnail single">
    <div class="image1">
        image 1
    </div>
</div>

<h2>Image Only</h2>

<div class="thumbnail">
    <div class="image1">
        image 1
    </div>
</div>

Thanks,

Mike

4 Answers

A generic answer is no but for your particular case you can do the background part like below:

div.thumbnail {
  background-color: green;
  padding: 1em;
  position:relative; /* relative here */
  z-index:0;
}

div.thumbnail.single {
  background-color: blue;
}
/* a pseudo element applied to text that will play the role of your background layer */
div.thumbnail div.text::before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background-color: black;
}
/**/

div.thumbnail div.image1 {
  background-color: cyan;
}

div.thumbnail div.text {
  background-color: orange;
}

div.thumbnail div.text span.title {
  background-color: red;
}
<h2>Image and Text</h2>

<div class="thumbnail">
  <div class="image1">
    image 1
  </div>
  <div class="text">
    text
  </div>
</div>

<h2>Image Only (Single)</h2>

<div class="thumbnail single">
  <div class="image1">
    image 1
  </div>
</div>

<h2>Image Only</h2>

<div class="thumbnail">
  <div class="image1">
    image 1
  </div>
</div>

:has is coming someday, maybe. In the meantime not really, though in certain use cases you might be be able to make something work with :empty or :not

From what I have found the only way now is to use a subclass. So div.thumbnail.single is the way to go.

Related