开关动态图
这个开关的效果主要运用了伪元素,CSS3伪元素是用来添加一些选择器的特殊效果。
一、定义以及用法
常见伪元素——::first-letter,::first-line,::before,::after,::selection。
::before和::after下特有的content,用于在css渲染中向元素逻辑上的头部或尾部添加内容。
注意:
- 这些添加不会出现在DOM中,不会改变文档内容,不可复制,仅仅是在css渲染层加入。
- ::before和::after必须配合content属性来使用,content用来定义插入的内容,content必须有值,至少是空。
- 默认情况下,伪类元素的display是默认值inline,可以通过设置display:block来改变其显示。
二、conter的取值以及用法
- content可取值string、attr(调用当前元素的属性)、URL/URI(content:url())
<style type="text/css">
a::after{
content: "(" attr(href) ")";
}
</style>
<a href="http://www.cnblogs.com/starof">starof</a>
- conter的用途——不使用列表元素实现序号功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body{
counter-reset: section;
}
h1{
counter-reset: subsection;
}
h1:before{
counter-increment:section;
content:counter(section) "、";
}
h2:before{
counter-increment:subsection;
content: counter(section) "." counter(subsection) "、";
}
</style>
</head>
<body>
<h1>HTML tutorials</h1>
<h2>HTML Tutorial</h2>
<h2>XHTML Tutorial</h2>
<h2>CSS Tutorial</h2>
<h1>Scripting tutorials</h1>
<h2>JavaScript</h2>
<h2>VBScript</h2>
<h1>XML tutorials</h1>
<h2>XML</h2>
<h2>XSL</h2>
</body>
</html>
了解更多伪元素用法请点击
三、开关效果源码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>纯css开关效果</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
label{
transform: scale(2);
width: 100px;
height: 50px;
border: 1px solid #ddd;
border-radius: 25px;
position: relative;
background-color: #DDDDDD;
overflow: hidden;
}
label input{
visibility: hidden;
}
/*按钮制作*/
label input::after{
visibility: visible;
content: '';
width: 40px;
height: 40px;
position: absolute;
left: 5px;
top: 5px;
background-color: #fff;
border-radius: 50%;
transition: all 0.2s;
}
/*按钮点击后向左移动*/
label input:checked::after{
transform: translateX(50px);
}
/*按钮后的框子制作*/
label input::before{
content: '';
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
visibility: visible;
transition: all 0.2s;
}
/*按钮后的框子点击后颜色的变化*/
label input:checked::before{
background: rgb(68,170,90);
}
</style>
</head>
<body>
<label>
<input type="checkbox" class="checkbox" />
</label>
</body>
</html>