【发布时间】:2021-03-03 14:12:35
【问题描述】:
*, *::after {
box-sizing: border-box;
transition-property: all;
transition-duration: 0.5s;
}
html, body {
margin: 0;
font-family: Arial;
text-transform: capitalize;
}
input { display: none; }
hr, label, label::after {
display: block;
width: 6rem;
height: 6rem;
border-style: none;
background-color: #444;
border-radius: 1rem;
}
div, section {
display: flex;
justify-content: center;
align-items: center;
margin: 0 1rem;
}
label, label::after {
position: relative;
width: 3rem;
height: 2rem;
margin: 1rem;
background-color: #eee;
content: '';
}
<style>
label {
cursor: pointer;
}
label::after {
transform: scale( 0.6 );
left: 0rem;
width: 2rem;
margin: 0;
background-color: #fff;
}
label:hover { background-color: #ddd; }
#blue:checked ~ div [ for='blue' ],
#red:checked ~ div [ for='red' ] {
background-color: #222;
}
#blue:checked ~ div [ for='blue' ]::after,
#red:checked ~ div [ for='red' ]::after {
left: 1rem;
}
#blue:checked ~ div [ for='blue' ]:hover,
#red:checked ~ div [ for='red' ]:hover {
background-color: #000;
}
#blue:checked ~ hr { background-color: #0be; }
#red:checked ~ hr { background-color: #d02; }
</style>
<input type='checkbox' id='blue'> <input type='checkbox' id='red'> <hr>
<div>
<section> <h2>blue</h2> <label for='blue'></label> </section>
<section> <h2>red</h2> <label for='red'></label> </section>
</div>
checkbox hack 可用于创建纯 CSS 切换,如下面的开/关开关所示。这个功能可以扩展到文档中的其他元素,利用 ~ 同级选择器,当下面的框根据是否选中开关改变颜色时会发生这种情况。
问题是:如果两个切换都被选中,有没有办法让 CSS 将框染成紫色?
这似乎是一种条件问题,例如,如果仅选中第一个框然后正常着色,但是如果同时选中两个框,则对框进行不同的着色。
也许只有当两个切换都打开时,使用几种叠加和混合模式才能使框变成紫色?我正在寻找仅 CSS 的解决方案。非常感谢任何帮助。
【问题讨论】:
标签: html css checkbox toggle togglebutton