html – CSS selector changing value if it contains an element

Question:

When choosing any selector definition, it is possible to set styles for each element that it is defined.

My doubt would be, instead of selecting an element and changing properties for itself, I would choose to search for an element and, if found, set properties for another element with a pre-defined class.

In summary if .area{} contains div .popup{} area receives overflow: hidden , otherwise overflow auto

Exemplifying in HTML:

<div class="area">
    <div class="popup"></div> <!-- contem entao: overflow: hidden -->
</div>

<div class="area"></div> <!-- nao contem entao: overflow: auto -->
<div class="popup"></div> 

The div .area depends on the div .popup to exist.

:has or :contains

These are not valid selectors.

of course it could be controlled by JS, but I take more into account the use of styling, or if there is a more correct way to do this it is also valid.

Answer:

A way using only css that could possibly solve your problem would be the following solution below, using the css3 :empty selector, which applies a certain css if the selected element does not have any child elements contained within it.

.area {
  height: 100px;
  margin-bottom: 10px;
  background: #bbb;
  /*contem entao: overflow: hidden*/
  overflow: hidden;
}

.area:empty {
  background: #f00;
  /*nao contem entao: overflow: auto*/
  overflow: auto;
}
<div class="area">
    <div class="popup"></div> <!-- contem entao: overflow: hidden -->
</div>

<div class="area"></div> <!-- nao contem entao: overflow: auto -->

However, this solution may solve your problem, but it will only work if the element with class .area , is always empty, without any sub-elements inside it.

However, in case the above solution doesn't address your problem, you wouldn't have a way to do what you want just using CSS2 or CSS3 . As css currently does not work with kin selection, this may possibly be implemented in future versions of it.

So a good solution to your problem would be using Javascript and jQuery .

Below is a simple example using jQuery :

$(function() {

  $('.area').each(function() {

    var child = $(this).children('.popup');
    
    if (child.length == 0) {
    	$(this).addClass('has-no-popup');
    }

  });
  
});
.area {
  height: 100px;
  margin-bottom: 10px;
  background: #bbb;
  /*contem entao: overflow: hidden*/
  overflow: hidden;
}

.has-no-popup {
  background: #f00;
  /*nao contem entao: overflow: auto*/
  overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="area">
    <div class="popup"></div> <!-- contem entao: overflow: hidden -->
</div>

<div class="area"></div> <!-- nao contem entao: overflow: auto -->
Scroll to Top
AllEscort