【问题标题】:Any way to set parent background-color on the basis of child class using css?有什么方法可以使用css根据子类设置父背景颜色?
【发布时间】:2021-02-10 04:20:27
【问题描述】:

有没有办法在子类的基础上使用 css 设置父背景颜色?

这是我的代码 https://jsbin.com/bahodalila/edit?html,css,js,output 如果孩子有red 班级父母应该设置background-color 红色。如果孩子有yellow 班级父母应该设置background-color 黄色。

<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
}

在这种情况下我会使用javascript 吗?有什么方法可以使用css 吗?

【问题讨论】:

标签: javascript html jquery css flexbox


【解决方案1】:

一个伪元素可以模拟这个:

.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>

【讨论】:

    【解决方案2】:

    CSS 和 DIV 不使用父子方法。您需要在 CSS 中创建每个变量,并将每个 DIV 设置为您想要的 CSS 变量。我用你的代码做了一个例子来展示。

    .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>

    【讨论】:

      【解决方案3】:

      不幸的是,css 上没有父 selectors。解决方法仅适用于 JS。你可以这样做:

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

      【讨论】:

        猜你喜欢
        • 2021-07-09
        • 1970-01-01
        • 2019-06-20
        • 2012-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-09
        相关资源
        最近更新 更多