1. :first-line
向元素的首行文本添加样式,不必关心首行是元素节点还是文本节点
<style> body,htm,div,p{ margin:0; padding:0; } div{ width:100px; height:100x; background-color:#FC9; } p{ height:50px; text-align:center; line-height:50px; } div > p:first-child{ background-color:#F90 } div > p:last-child{ background-color:#6CC } div:first-line{ color:red; background-color:green; /*这段设置无效 display:block; width:100px; height:100px;*/ } </style> <div> <p>p1</p> <p>p2</p> </div>
:first-line伪元素相当于给文本添加了span元素<p><span>p1</span></p>,而且CSS代码中设置display:block是无效的
<style> body,htm,div,p{ margin:0; padding:0; } div{ width:100px; height:100x; background-color:#FC9; } p{ height:50px; text-align:center; line-height:50px; } div > p:first-child{ background-color:#F90 } div > p:last-child{ background-color:#6CC } div:first-line{ color:red; background-color:green; /*这段设置无效 display:block; width:100px; height:100px;*/ } </style> <div> This is first line <p>p1</p> <p>p2</p> </div>
由于文本超过div的宽度,换行后,只有第一行有效果
2. :first-letter
向文本的第一个字母添加特殊样式
<style> div:first-letter{ color:red; } </style> <div> This is first line <p>p1</p> <p>p2</p> </div>
默认的display:inline,但是:first-letter不能通过display:block来改变显示方式
3. :before 表示在元素的内容之前新插入内容
:after 表示在元素的内容之后新插入内容
多个内容以空格分隔 content:"hahah" attr(class) url(images/15.gif);
3.1 插入图片
<style> div:before{ content:url(images/15.gif); border:10px solid red; } span{ border:10px solid green; } </style> <div> <span>This is first line</span> <p>p1</p> <p>p2</p> </div>
:after默认插入的元素是inline属性的,通过修改display:block来改成块级元素
<style> div:before{ content:url(images/15.gif); border:10px solid red; display:block; width:100px; height:50px; } span{ border:10px solid green; } </style> <div> <span>This is first line</span> <p>p1</p> <p>p2</p> </div>
3.2 插入文本
<style> div{ width:300px; height:300px; background-color:#FC9; text-align:center; } div:hover:after{ content:"This is after"; background-color:green; width:100px; height:100px; display:block; margin:0 auto; } </style>
鼠标移动到div上时:
3.3 插入特殊图标
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .phoneNumber:before{ content:"\260E"; font-size:15px; } </style> </head> <body> <p class="phoneNumber">13021020<span>☎</span>394</p> </body> </html>
3.4 通过attr()调用当前元素的属性(参数不是字符串)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> div{ color:red; font-size:1.5em; } div:after{ content:attr(id); color:yellow; } </style> </head> <body> <div id='myDiv' style="width:100px;height:100px;background-color:cyan">DIV<br/></div> </body> </html>