简体   繁体   English

在 CSS 中签入时将背景颜色更改为粉红色

[英]Change Background color to pink when checked in CSS

If I click the checkbox the background-color won't change to pink, what am I doing wrong here?如果我单击复选框, background-color不会变为粉红色,我在这里做错了什么? Everytime I click the checkbox nothing happens.每次我单击复选框时都没有任何反应。

 .joe:checked~.sub { background-color: pink; }.sub { position: absolute; background-color: grey; top: 70px; right: 395px; width: 185px; display: flex; flex-direction: column; justify-content: center; align-items: center; }
 <input type="checkbox" id="hoon" class="joe"> <li><a href="#"><label for="hoon">Services</label></a></li> <div class="sub"> <li><a href="#">Take aways</a></li> <li><a href="#">Online Order</a></li> <li><a href="#">Pick and Drop</a></li></div>

There is no .sub class defined in your above example.上面的示例中没有定义.sub class 。 If that wasn't intentional, then the issue is with your CSS selector precedence level.如果这不是故意的,那么问题出在您的 CSS 选择器优先级上。

Your CSS should've been:您的 CSS 应该是:

.sub{
    position: absolute;
    background-color: grey;
    top: 70px;
    right: 395px;
    width: 185px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.joe:checked ~ .sub{
    background-color: pink;
}

The difference in above css from your one is that, .joe:checked ~.sub selector styles are written post .sub class styles. The difference in above css from your one is that, .joe .joe:checked ~.sub selector styles are written post .sub class styles. It helps CSS to override the older .sub class styles.它有助于 CSS 覆盖旧的.sub class styles。

Details on CSS Precedence: Precedence in CSS有关 CSS 优先级的详细信息: CSS中的优先级

Solved:解决了:

Codesandbox Example 代码沙盒示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM