:after
CSS伪元素::after
用来创建一个伪元素,作为已选中元素的最后一个子元素。通常会配合content
属性来为该元素添加装饰内容。这个虚拟元素默认是行内元素。
特点
- 伪元素不属于文档,所以js无法操作它
- 伪元素属于主元素的一部分,因此点击伪元素触发的是主元素的click、hover等事件,主元素的继承样式对子元素生效,当主元素设置
overflow: hidden
时,伪元素超出主元素的部分无法显示 - 无法为伪元素设置hover等伪类
- 伪元素默认为行内元素
- 注意:如需设置transform属性,需要对伪元素添加display: block/inline-block
优点
减少dom节点数
让css帮助解决部分js问题,让问题变得简单
缺点
不利于SEO
无法审查元素,不利于调试
基本使用
<span class="ribbon">Notice where the orange box is.</span>
.ribbon {
background-color: #5BC8F7;
}
.ribbon::after {
content: "Look at this orange box.";
background-color: #FFBA10;
border-color: black;
border-style: dotted;
}
相当于
<span class="ribbon">Notice where the orange box is. <span class="ribbon-orange"> Look at this orange box.</span></span>
.ribbon {
background-color: #5BC8F7;
}
.ribbon-orange {
background-color: #FFBA10;
border-color: black;
border-style: dotted;
}
其它示例
示例1 提示文字(来自MDN)
<p>这是上面代码的实现<br />
我们有一些 <span data-descr="collection of words and punctuation">文字</span> 有一些
<span data-descr="small popups which also hide again">提示</span>。<br />
把鼠标放上去<span data-descr="not to be taken literally">看看</span>。
</p>
span[data-descr] {
position: relative;
text-decoration: underline;
color: #00F;
cursor: help;
}
span[data-descr]:hover::after {
content: attr(data-descr);
position: absolute;
left: 0;
top: 24px;
min-width: 200px;
border: 1px #aaaaaa solid;
border-radius: 10px;
background-color: #ffffcc;
padding: 12px;
color: #000000;
font-size: 14px;
z-index: 1;
}
示例2 css画叉
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.right-x {
display: inline-block;
margin-top: 50px;
margin-left: 50px;
/* //改叉叉大小 6:1等量放大缩小就行(算好的,省的自己调整太麻烦) */
width: 180px;
height: 30px;
background: #999;
line-height: 0;
font-size: 0;
vertical-align: middle;
transform: rotate(45deg);
-webkit-transform: rotate(45deg);
}
.right-x:after {
content: "";
display: inline-block;
/* //改叉叉大小 6:1等量放大缩小就行(这里也要改) */
width: 180px;
height: 30px;
background: #999;
transform: rotate(-90deg);
-webkit-transform: rotate(-90deg);
}
</style>
</head>
<body>
<div class="right-x"></div>
</body>
</html>
:before
CSS 中,::before 创建一个伪元素,其将成为匹配选中的元素的第一个子元素。常通过 content 属性来为一个元素添加修饰性的内容。此元素默认为行内元素。
其它与:after一致。