gpt4 book ai didi

javascript - 有什么方法可以使用css在子类的基础上设置父背景颜色?

转载 作者:行者123 更新时间:2023-12-04 08:41:13 28 4
gpt4 key购买 nike

有没有办法使用css根据子类设置父背景颜色?
这是我的代码
https://jsbin.com/bahodalila/edit?html,css,js,output
如果 child 有 red类(class)家长应该设置 background-color红色。如果 child 有yellow类(class)家长应该设置 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 ?

最佳答案

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

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

关于javascript - 有什么方法可以使用css在子类的基础上设置父背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64562043/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com