如何更改内部切换背景颜色

时间:2021-06-16 12:03:59

标签: css

我正在尝试更改内部切换颜色,绿色然后选中其他深灰色。我不想改变指标本身的颜色。我该怎么做?

到目前为止,我尝试添加 toggle:checked 颜色,但它似乎位置错误,因为没有任何变化。

.toggle-view {
    display: inline-flex;
    align-items: center;
    cursor: pointer;
    color: #394a56;
  }
  
  .toggle {
    position: absolute;
    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;
  }
  
  .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="toggle-view" id="toggle-darkmode">
  <div class="toggle">
    <input class="toggle-state" type="checkbox" checked/>
    <div class="indicator"></div>
  </div>
</label>

1 个答案:

答案 0 :(得分:2)

label(在我的例子中为 toggle-container 元素)内添加一个 div 并定位该 div 以适应 widthheightlabel使用 position: absolute;。为输入的相邻元素添加 CSS。对于检查输入给出 background: green,对于正常输入 background: gray

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

.toggle {
  position: absolute;
  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;
}

.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);
} 

.toggle-container {
  position: absolute;
  width: 100%;
  height: 100%;
}

.toggle-state + .toggle-container {
  background: grey;
}

.toggle-state:checked + .toggle-container {
  background: green;
}
<label class="toggle-view" id="toggle-darkmode">
  <div class="toggle">
    <input class="toggle-state" type="checkbox" checked />
    <!-- Custom container -->
    <div class="toggle-container"></div>
    <div class="indicator"></div>
  </div>
</label>