伪元素介绍
- E::before和E::after
在E元素内部的开始位置和结束位创建一个元素,该元素为行内元素,且必须要结合content属性使用。
div::before {
content:"开始";
}
div::after {
content:"结束";
}
-
":" 与 “::” 区别在于区分伪类和伪元素,E:after、E:before 在旧版本里是伪元素,CSS3的规范里“:”用来表示伪类,“::”用来表示伪元素,但是在高版本浏览器下E:after、E:before会被自动识别为E::after、E::before,这样做的目的是用来做兼容处理。
-
之所以被称为伪元素,是因为他们不是真正的页面元素,html没有对应的元素,但是其所有用法和表现行为与真正的页面元素一样,可以对其使用诸如页面元素一样的css样式,表面上看上去貌似是页面的某些元素来展现,实际上是css样式展现的行为,因此被称为伪元素。是伪元素在html代码机构中的展现,可以看出无法伪元素的结构无法审查。
常用用途
- 用于添加图标字体,即iconfont。
- 伪元素清除浮动。
.clearfix:before,.clearfix:after {
content:"";
display:table;
height: 0; // 须为需要清除浮动元素的伪对象中设置 height:0,否则该元素会比实际高出若干像素
}
.clearfix:after {
clear:both;
}
.clearfix {
*zoom:1;
}
优惠券案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>优惠券</title>
<style>
* {
margin: 0;
padding: 0;
}
.coupon-box {
width: 260px;
height: 150px;
background: #e92322;
margin: 100px auto;
font-size: 16px;
}
.coupon-left {
overflow: hidden;
}
.coupon-right {
float: right;
width: 60px;
height: 150px;
text-align: center;
position: relative;
border-left: 1px dashed #fff;
}
/*两个凹进去的圆*/
.coupon-right::before,.coupon-right::after{
content: '';
position: absolute;
width: 12px;
height: 12px;
border-radius: 50%;
background: #fff;
left: -6px;
}
.coupon-right::after{
bottom: -6px;
box-shadow: 0 2px 3px #d8d8d8 inset;
}
.coupon-right::before{
top: -6px;
box-shadow: 0 -2px 3px #d8d8d8 inset;
}
.coupon-right div {
width: 20px;
color: #fff;
font-size: 20px;
margin-left: 20px;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="coupon-box">
<div class="coupon-right">
<div>立即领取</div>
</div>
<div class="coupon-left">
<div>
<h3>优惠券内容</h3>
</div>
</div>
</div>
</body>
</html>
效果图: