简介
伪元素可以用于定位文档中包含的文本,在CSS3中伪元素主要有 ::first-letter, ::first-line, ::before, ::after, ::selection, 下面逐个说明其用途。
::first-letter
用来选择文本块的第一个字母,通常用于给文本元素增加排版细节。如下程序实现首字母下沉。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试伪元素的使用</title>
<style type="text/css">
p:first-child::first-letter {
float: left;
color: #903;
padding: 4px 8px 0px 3px;
font: 75px/60px georgia;
}
</style>
</head>
<body>
<div>
<p>
In the beginning was the Word.
</p>
</div>
</body>
</html>
显示效果如下:
::first-line
用来匹配文本元素的第一行文本,下面的例子将第一行文本设置为红色斜体:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试伪元素的使用</title>
<style type="text/css">
p:first-child::first-line {
font: italic 16px/18px Georgia;
color: #903;
}
</style>
</head>
<body>
<div>
<p>
In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.
</p>
</div>
</body>
</html>
显示效果如下:
::before和::after
用于在元素内容之前或者之后生成新的内容,例如,下面的代码在超链接后面放上链接的url:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试伪元素的使用</title>
<style type="text/css">
a[href^=http]::after {
content: "(" attr(href) ")";
}
</style>
</head>
<body>
<div>
<a href="http://www.sina.com">sina</a>
</div>
</body>
</html>
显示效果如下:
::selection
用来匹配被选中的文本,浏览器中被选中的文字默认的一般是蓝色背景和白色的文字,下面的程序将其样式改为背景红色,文字白色:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试伪元素的使用</title>
<style type="text/css">
::selection {
background: red;
color: #fff;
}
</style>
</head>
<body>
<div>
<p>In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.In the beginning was the Word.</p>
</div>
</body>
</html>
显示效果如下: