为什么更改背景颜色会阻止此CSS切换按钮正常工作

时间:2018-12-28 05:48:07

标签: html css css3

试图修改此CSS单选按钮:link

如果我更改主体的背景,则可以正常工作,但是如果我将代码包装在NSAttributedString中并更改了div的背景,则过渡将停止工作。有什么解释?我认为这与div的背景转换有关,但是当我尝试使用它时,我无法使其正常工作。我将如何解决这个问题,使其在任何背景下都能正常工作?

这是HTML

.btn

和CSS(已从链接更改为常规CSS)

<input id="toggle-on" class="toggle toggle-left" name="toggle" value="false" type="radio" checked>
<label for="toggle-on" class="btn">Yes</label>
<input id="toggle-off" class="toggle toggle-right" name="toggle" value="true" type="radio">
<label for="toggle-off" class="btn">No</label>

1 个答案:

答案 0 :(得分:2)

这是因为在z-index: -1body上设置了html。如果将切换按钮包裹在div元素中,并将div元素的z-index值设置为低于bodyhtml,则您将能够实现自己追求的目标。像这样:

body, html {
  background: #efefef;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100%;
  z-index: -1;
}
div {
    background-color: tomato;
    z-index: -2;
}
.btn {
  border: 3px solid #1a1a1a;
  display: inline-block;
  padding: 10px;
  position: relative;
  text-align: center;
  transition: background 600ms ease, color 600ms ease;
}
input[type="radio"].toggle {
  display: none;
}
input[type="radio"].toggle + label {
  cursor: pointer;
  min-width: 60px;
}
input[type="radio"].toggle + label:hover {
  background: none;
  color: #1a1a1a;
}
input[type="radio"].toggle + label:after {
  background: #1a1a1a;
  content: "";
  height: 100%;
  position: absolute;
  top: 0;
  transition: left 200ms cubic-bezier(0.77, 0, 0.175, 1);
  width: 100%;
  z-index: -1;
}
input[type="radio"].toggle.toggle-left + label {
  border-right: 0;
}
input[type="radio"].toggle.toggle-left + label:after {
  left: 100%;
}
input[type="radio"].toggle.toggle-right + label {
  margin-left: -5px;
}
input[type="radio"].toggle.toggle-right + label:after {
  left: -100%;
}
input[type="radio"].toggle:checked + label {
  cursor: default;
  color: #fff;
  transition: color 200ms;
}
input[type="radio"].toggle:checked + label:after {
  left: 0;
}
<div>
    <input id="toggle-on" class="toggle toggle-left" name="toggle" value="false" type="radio" checked>
    <label for="toggle-on" class="btn">Yes</label>
    <input id="toggle-off" class="toggle toggle-right" name="toggle" value="true" type="radio">
    <label for="toggle-off" class="btn">No</label>
</div>