层叠样式表(CSS)的主要目的是给HTML元素添加样式,然而,在一些案例中给文档添加额外的元素是多余的或是不可能的。事实上CSS中有一个特性允许我们添加额外元素而不扰乱文档本身,这就是“伪元素”。
:before 选择器在被选元素的内容前面插入内容。
:after 选择器在被选元素的内容后面插入内容。
用来清除浮动
.clearfix:after{display:block;visibility:hidden;clear:both;height:0;content:'.';font-size:0}
用来插入图标
我用的before
我用的after
.test-icon:before,
.test-icon1:after{
display:inline-block;
content:'';
width:16px;
height:16px;
vertical-align:middle;
background:url(https://www.eqifei.net/favicon.ico)
}
content的特殊用法attr:鼠标移上去显示tips效果
鼠标移到我这里就能看到效果
.testTips{position:relative;display:inline-block;margin-top:20px}
.testTips:hover{cursor:pointer}
.testTips:hover:before{content:attr(data-test);background-color:#2085c5;border-radius:3px;color:#fff;padding:10px;position:absolute;left:100%;top:-70%;margin-left:8px;white-space:pre}
.testTips:hover:after{content:"";position:absolute;width:0;height:0;border-right:8px solid #2085c5;border-top:8px solid transparent;border-bottom:8px solid transparent}
content的特殊用法attr:制作半边文字
W E B 前 端
W
E
B
前
端
.testHalf span{position:relative;display:inline-block;font-size:80px;color:#000;overflow:hidden}
.testHalf span:before{display:block;z-index:1;position:absolute;top:0;left:0;width:50%;content:attr(data-content);overflow:hidden;color:#f00}