2

is there any way to set parent background-color on the basis of child class using css?

here is my code https://jsbin.com/bahodalila/edit?html,css,js,output if child have red class parent should set background-color red.If child have yellow class parent should set background-color yellow.

<div class="par">
    
    <div class="red">
      helli
    </div>
  </div>



.par{
  background-color:red;
}

.par{
  background-color:yellow;
}
.par{
  width:200px;
  height:200px;
  border:1px solid blue;
  
}


.red{
  width:100px;
  height:100px;
  color:red;
  border:1px solid;
  background-color:green
}

will I use javascript in this case ? is there any way to using css ?

user5711656
  • 3,310
  • 4
  • 33
  • 70
  • Does this answer your question? [Is there a CSS parent selector?](https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – David Liang Oct 27 '20 at 20:19

3 Answers3

2

A pseudo element can simulate this:

.par {
  width: 200px;
  height: 200px;
  border: 1px solid blue;
  position:relative; /* here and not on child to make it relative to parent*/
  z-index:0;
}

.red {
  width: 100px;
  height: 100px;
  color: red;
  border: 1px solid;
  background-color: green;
}
.red::before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:inherit;
}
<div class="par">

  <div class="red">
    helli
  </div>
</div>


<div class="par">

  <div class="red" style="background:blue;">
    helli
  </div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
0

CSS and DIV do not use the parent-child methodology. You will need to create each variable in CSS and set each DIV to the CSS variable you want. I did an example using your code to show.

.par{
  background-color:red;
  width:200px;
  height:200px;
  border:1px solid blue;
}

.par-yellow{
  background-color:yellow;
  width:150px;
  height:150px;
  border:1px solid;
}

.red{
  width:100px;
  height:100px;
  color:red;
  border:1px solid;
  background-color:green
}
<div class="par">
  <div class="par-yellow">    
    <div class="red">
      helli
    </div>
    </div>
  </div>
0

Unfortunately there are no parent selectors on css. A workaround is only with JS posible. You could do something like:

var redElements = document.querySelectorAll(".red");
for(var i = 0; i < redElements.length; i++){
  redElements[i].parentElement.style.backgroundColor = "red";
}
Andres Abadia
  • 817
  • 7
  • 14