:before和:after的作用就是在指定的元素内容(而不是元素本身)之前或者之后插入一个包含content属性指定内容的行内元素(默认是行内),最基本的用法如下:
#example:before {
content: "#";
color: red;
}
#example:after {
content: "$";
color: red;
}
这段代码会在#example元素内容之前插入一个'#',以及在内容之后添加一个'$',插入的行内元素是作为#example的子元素
需要注意的是如果没有content属性,伪类元素将没有任何作用。但是可以指定content为空,同时正如前面所说,插入的内容默认是一个行内元素,并且在HTML源代码中无法看到,这就是为什么称之为伪类元素的理由,所以也就无法通过DOM对其进行操作。
#example:before {
content: "";
display: block;
width: 100px;
height: 100px;
}
伪类元素也会像其他子元素一样正常继承父元素的一些CSS属性,比如字体等。
除了插入文字内容,还可以指定其他内容:
p:before {
content: url('img.jpg');
}
a:after {
content: attr(href);
}
attr()函数会返回指定元素对应属性的值
最后,奉上最惦记的浏览器支持情况
- Chrome 2+,
- Firefox 3.5+ (3.0 had partial support),
- Safari 1.3+,
- Opera 9.2+,
- IE8+ (with some minor bugs),
- Pretty much all mobile browsers.
放在伪类元素里面的内容一般都只是装饰性的,所以即便是IE6/7不支持也应该能降级到正常显示主体内容。
:before和::before区别
伪元素(双冒号),css3中的伪类是(单冒号)
用法:
1、实现八卦图
'#yin-yang {
width: 96px;
height: 48px;
background: #eee;
border-color: red;
border-style: solid;
border-width: 2px 50px 2px 2px;
border-radius: 100%;
position: relative;
}
(原来border-bottom=50px是这个效果,注意圆的长度也长了)
#yin-yang:before {
content: "";
position: absolute;
top: 50%;
left: 0;
background: #eee;
border: 18px solid red;
border-radius: 100%;
width: 12px;
height: 12px;
}
#yin-yang:after {
content: "";
position: absolute;
top: 50%;
left: 50%;
background: red;
border: 18px solid #eee;
border-radius:100%;
width: 12px;
height: 12px;
}
2、对话框
<style> .test-div{ position: relative; /*日常相对定位*/ width:150px; height: 36px; border:black 1px solid; border-radius:5px; background: rgba(245,245,245,1) } .test-div:before,.test-div:after{ content: ""; /*:before和:after必带技能,重要性为满5颗星*/ display: block; position: absolute; /*日常绝对定位*/ top:8px; width: 0; height: 0; border:6px transparent solid; } .test-div:before{ left:-11px; border-right-color: rgba(245,245,245,1); z-index:1 } .test-div:after{ left:-12px; border-right-color: rgba(0,0,0,1); z-index: 0 } </style> <div class="test-div"></div>
3、清除浮动