Hello everyone, I come again, this time to show you the use of pure CSS switch effect

The first is conception

We use the tag to achieve this effect. The checkbox features correspond to the switch on and off. On: the switch is on. Off: the switch is off

<label for="ck2">
  <input type="checkbox" id="ck2"> < SPAN > Unselected, the switch is turned off </span> </label> <br> <labelfor="ck1">
  <input type="checkbox" id="ck1"Checked < SPAN > turn on the switch </span> </label>Copy the code

Start sketching out the off and on states

Here is a description of the position implemented using position. If you don’t know, you can open MDN to view relevant knowledge

<P>off status sketch </P> <div class="toggle">
  <div class="cookie"></div> </div> <br> <P>on Status sketch </P> <div class="toggle2">
  <div class="cookie2"></div>
</div>
Copy the code
.toggle{
  display:inline-block;
  position:relative;
  height:25px;
  width:50px;  
  border-radius:4px;
  background:#CC0000;
}
.cookie{
  position:absolute;
  left:2px;
  top:2px;
  bottom:2px;
  width:50%;
  background:rgba(230,230,230,0.9);
  border-radius:3px;
}
.toggle2{
  display:inline-block;
  position:relative;
  height:25px;
  width:50px; 
  padding:2px;
  border-radius:4px;
  background:#66CC33;  
}
.cookie2{
  position:absolute;
  right:2px;
  top:2px;
  bottom:2px;  
  width:50%;
  background:rgba(230,230,230,0.9);
  border-radius:3px;
}
Copy the code

Then we put the two sketches inside the label

<label for="ck4">
  <input type="checkbox" id="ck4">
  <div class="toggle">
    <div class="cookie"></div>
  </div>
</label>
<br>
<label for="ck3">
  <input type="checkbox" id="ck3" checked>
  <div class="toggle2">
    <div class="cookie2"></div>
  </div>
</label>
Copy the code

Collate and optimize CSS with label and checkBox

<label for="ck5">
  <input type="checkbox" id="ck5">
  <div class="toggle-finish">
    <div class="cookie-finish"></div>
  </div>
</label>
<br>
<label for="ck6">
  <input type="checkbox" id="ck6" checked>
  <div class="toggle-finish">
    <div class="cookie-finish"></div>
  </div>
</label>
Copy the code
.toggle-finish{
  cursor:pointer;
  display:inline-block;
  position:relative;
  height:25px;
  width:50px;  
  border-radius:4px;
  background:#CC0000;
}
.cookie-finish{
  position:absolute;
  left:2px;
  top:2px;
  bottom:2px;
  width:50%;
  background:rgba(230,230,230,0.9);
  border-radius:3px;
}
input:checked + .toggle-finish{
  background:#66CC33;  
}
input:checked + .toggle-finish .cookie-finish{ 
  left:auto;
  right:2px;
}
Copy the code

Codepen. IO /Ritr/pen/Wq…

I also optimized an animated codepen. IO /Ritr/pen/LK…