CSS 没有 类 / id 的拨动开关

CSS Toggle Switch without classes / id

我现在正在为我大学的网络工程课程做一个项目。我们必须创建某种学校管理站点,现在,只允许使用纯 HTML 和 CSS,但我们在 CSS 中工作而没有 类和 ids ,只允许选择器。

现在我想在我们的页面上添加一个切换按钮,我找到了这个网站 (https://proto.io/freebies/onoff/),您可以在其中创建自己的切换按钮。但是您收到的代码与我不允许使用的 类 一起使用,所以我试图更改代码,以便它只使用选择器,但它不会工作。 也许有人可以在这里帮助我理解我的错误(除了复制代码片段而不是解决问题)。

div:last-of-type {
  position: relative;
  width: 67px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}
input[type="checkbox"] {
  display: none;
}
label {
  display: block;
  overflow: hidden;
  cursor: pointer;
  height: 22px;
  padding: 0;
  line-height: 22px;
  border: 2px solid #CCCCCC;
  border-radius: 22px;
  background-color: #FA1212;
  transition: background-color 0.3s ease-in;
}
label:before {
  content: "";
  display: block;
  width: 22px;
  margin: 0px;
  background: #FFFFFF;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 43px;
  border: 2px solid #CCCCCC;
  border-radius: 22px;
  transition: all 0.3s ease-in 0s;
}
input[type="checkbox"]:checked + label {
  background-color: #28CF25;
}
input[type="checkbox"]:checked + label,
input[type="checkbox"]:checked +label:before {
  border-color: #28CF25;
}
input[type="checkbox"]:checked + label:before {
  right: 0px;
}
<div>
  <input type="checkbox" name="onoffswitch" checked>
  <label for="myonoffswitch"></label>
</div>

您不需要使用 类,只要标签具有与输入的 id="..." 相同的 for="...",并且标签正确显示 输入标签之后。

label 元素上的 for 属性链接到 input 元素上的 id 属性,剩下的由浏览器完成。

下面的快速演示演示了这一点:

html{background:rgba(0,0,0,0.4);text-align:center;font-size:2em;}
input:checked + label {
  background: lime;
}
input:checked + label {
  color: red;
}
input + label {
  display: inline-block;
  height: 40px;
  border-radius: 25px;
  width: 100px;
  background: tomato;
  position: relative;
  transition: all 0.4s;
  cursor: pointer;
  border: 5px solid lightgray;
  box-shadow: inset 2px 2px 5px black, 2px 2px 5px black;
}
input[type="checkbox"] {
  display: none;
}
input + label:before {
  content: "";
  position: absolute;
  background: white;
  height: 30px;
  width: 30px;
  top: 5px;
  transition: all 0.4s;
  left: calc(100% - 35px);
  border-radius: 50%;
  box-shadow: 2px 2px 5px black;
}
input:checked + label:before {
  left: 5px;
}
Click My toggle Checkbox
<br/><br/>
<div>
  <input type="checkbox" id="myonoffswitch" />
  <label for="myonoffswitch"></label>
</div>