纯css实现开关效果

大家好,我又来了,这次给大家表演使用纯css实现开关效果

首先是构思

我们使用标签来实现这个效果。
checkbox的选中、未选中的特性,刚好对应开关的打开、关闭
on:打开 off:关闭



开始画出off、on状态的草图

这里要讲解一下,使用了position来实现的定位。有不了解的同学可以打开MDN查看相关知识

off状态草图


on状态草图

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

然后我们将这两个草图放到label内



结合label和checkbox整理、优化css



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


到此为止就已经基本实现一个开关的功能了,记得将input隐藏起来哦
可以点击预览https://codepen.io/Ritr/pen/W...
另外我还优化了一个动画版
https://codepen.io/Ritr/pen/L...

你可能感兴趣的:(css,前端)