首页 > 解决方案 > css不能改变切换背景颜色

问题描述

我发现这是一个异态切换,如果选中,则无法弄清楚如何更改背景。我知道这个问题有多基本。我用基本的切换复选框做了几次,但似乎我很困惑,或者这种设计模式忽略了我的尝试。

到目前为止,我尝试了不同的解决方案:

input[type="checkbox"]:checked {
background: red
}

或者

.toggle:checked {
background: red
}

不幸的是,他们都没有完成这项工作。我知道这是一个基本问题,并认为你们可以在我苦苦挣扎时指导我找到正确的解决方案。

body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  font-family: 'IBM Plex Sans Condensed', sans-serif;
  font-weight: 300;
  background-color: #ecf0f3;
}

.label {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  color: #394a56;
}

.label-text {
  margin-left: 16px;
}

.toggle {
  position: relative;
  height: 30px;
  width: 60px;
  border-radius: 15px;
  overflow: hidden;
  box-shadow:
    -8px -4px 8px 0px #ffffff,
    8px 4px 12px 0px #d1d9e6,
    4px 4px 4px 0px #d1d9e6 inset,
    -4px -4px 4px 0px #ffffff inset;
}

.toggle-state {
  display: none;
}

input[type=checkbox] {
  background: yellow
}

.indicator {
  height: 100%;
  width: 200%;
  background: #ecf0f3;
  border-radius: 15px;
  transform: translate3d(-75%, 0, 0);
  transition: transform 0.4s cubic-bezier(0.85, 0.05, 0.18, 1.35);
  box-shadow:
    -8px -4px 8px 0px #ffffff,
    8px 4px 12px 0px #d1d9e6;
}

.toggle-state:checked ~ .indicator {
  transform: translate3d(25%, 0, 0);
}
<label class="label">
  <div class="toggle">
    <input class="toggle-state" type="checkbox" name="check" value="check" />
    <div class="indicator"></div>
  </div>
  <div class="label-text">change toggle background</div>
</label>

标签: htmlcss

解决方案


您正在尝试在输入上应用背景,但指标类正在覆盖它。为什么不将属性赋予指标类本身?

body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  font-family: 'IBM Plex Sans Condensed', sans-serif;
  font-weight: 300;
  background-color: #ecf0f3;
}

.label {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  color: #394a56;
}

.label-text {
  margin-left: 16px;
}

.toggle {
  position: relative;
  height: 30px;
  width: 60px;
  border-radius: 15px;
  overflow: hidden;
  box-shadow:
    -8px -4px 8px 0px #ffffff,
    8px 4px 12px 0px #d1d9e6,
    4px 4px 4px 0px #d1d9e6 inset,
    -4px -4px 4px 0px #ffffff inset;
}

.toggle-state {
  display: none;
}

input[type=checkbox] {
  background: yellow
}

.indicator {
  height: 100%;
  width: 200%;
  background: #ecf0f3;
  border-radius: 15px;
  transform: translate3d(-75%, 0, 0);
  transition: transform 0.4s cubic-bezier(0.85, 0.05, 0.18, 1.35);
  box-shadow:
    -8px -4px 8px 0px #ffffff,
    8px 4px 12px 0px #d1d9e6;
}

.toggle-state:checked ~ .indicator {
  transform: translate3d(25%, 0, 0);
  background: red;
}
<label class="label">
  <div class="toggle">
    <input class="toggle-state" type="checkbox" name="check" value="check" />
    <div class="indicator"></div>
  </div>
  <div class="label-text">change toggle background</div>
</label>


推荐阅读