<input type="checkbox" id="c1">
<label for="c1">c1</label>
<div>
<span></span>
<span></span>
</div>
我想在选中复选框时设置跨度样式。我尝试使用以下样式,但无法正常工作。
input:checked ~ div span{
background: red;
}
input:checked~div span {
background: red;
}
<input type="checkbox" id="c1">
<label for="c1">c1</label>
<div>
<span></span>
<span></span>
</div>
答案 0 :(得分:6)
在您的范围内放入一些内容,它可以正常工作。
input:checked ~ div span{
background: red;
}
<input type="checkbox" id="c1">
<label for="c1">c1</label>
<div>
<span>Red Text</span>
<span>Red alert</span>
</div>
答案 1 :(得分:3)
您在p标签中有一个div,这就是导致问题的原因,如下所示更改结构和CSS。
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.abc {
position: relative;
text-align: center;
height: 100px;
font: 100px/1em sans-serif;
top: 50vh;
transform: translateY(-50%);
}
input {
visibility: hidden;
}
label {
cursor: pointer;
}
input+label:before {
border: 1px solid #333;
content: "\00a0";
display: inline-block;
height: 100px;
width: 100px;
margin: 0 1em 0 0;
border-radius: 50%;
}
input:checked+label:before {
border: none;
background: #fff;
color: #333;
content: "\2713";
text-align: center;
}
input:checked+label:after {
font-weight: bold;
}
input:focus+label::before {
outline: rgb(59, 153, 252) auto 5px;
}
.def {
width: 100px;
height: 100px;
top: 50%;
left: 50%;
position: absolute;
transform: translate(-140%, -50%);
z-index: -1;
}
span {
background: green;
width: 20px;
height: 20px;
top: 50%;
left: 55%;
transform: translate(-50%, -55%);
position: absolute;
border-radius: 50%;
}
span:nth-child(1) {
left: 120%;
/* background:green; */
}
span:nth-child(2) {
top: 115%;
/* background:red; */
}
span:nth-child(3) {
left: -10%;
/* background:blue; */
}
span:nth-child(4) {
top: -10%;
/* background:yellow; */
}
/* styles for span when checkbox is checked */
input:checked~div span {
background: red;
}
<div class="abc">
<input type="checkbox" id="c1" />
<label for="c1">c1</label>
<div class="def">
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
答案 2 :(得分:2)
默认情况下,跨度内部没有任何内容,并且不占用任何空间。如果我在范围内添加文本,则您的代码对我有用。