What is the CSS selector to change a particular parent class only if it has a certain daughter class

Asked

Viewed 44 times

3

I have the following structure in HTML:

<div class="panel">
     ...
</div>

<div class="panel">
    <div class="controls"> 
       ...
    </div>
</div>

The class panel has some general styles and I would like to change the padding-right her only when she contains as her daughter the class controls.

I know if it was the other way around, if I wanted to change the class controls only if she were the daughter of panel, the selector in CSS would look:

.panel .controls {
  ...
}

Or:

.panel > .controls {
   ...
}

But and to change the class panel only if she has the class as her daughter controls? There’s a dial for that?

1 answer

1


Currently (May/2021) it is not possible to do this with CSS.

There is a this proposal for the pseudo-selector :has. With him it would be possible to have something like:

/* seleciona os elementos com a classe panel, mas só se tiver filho com a classe control */
.panel:has(> .controls) {
    estilos...
}

But that’s still is not supported by browsers. That is, for now there is no way to do with CSS, so an alternative would be to turn to Javascript. Ex:

// para todos os elementos com class=panel
for (const elemento of document.querySelectorAll('.panel')) {
    // verifica se tem controls dentro do elemento, e aplica um estilo diferente para cada caso
    if (elemento.querySelector('.controls')) { // tem
        elemento.style.color = "yellow";
    } else { // não tem
        elemento.style.color = "green";
    }
}
.panel {
  /* será sobrescrito pelo JavaScript */
  color: blue;
}

.panel .controls {
  color: red;
}
<div class="panel">
     verde
</div>

<div class="panel">
    amarelo
    <div class="controls"> 
       vermelho
    </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.