CSS3 伪元素(Pseudo-elements)大全
CSS3 伪元素用于选择元素的特定部分,以双冒号 ::
开头(CSS3 规范推荐写法,但单冒号 :
也支持以保持向后兼容)。
主要 CSS3 伪元素列表
::before
在元素内容前插入生成的内容p::before { content: "→ "; }
::after
在元素内容后插入生成的内容p::after { content: " ←"; }
::first-letter
选择块级元素的首字母p::first-letter { font-size: 2em; }
::first-line
选择块级元素的第一行p::first-line { font-weight: bold; }
::selection
选择用户选中的文本部分::selection { background: yellow; }
::placeholder
选择表单元素的占位文本input::placeholder { color: #999; }
::backdrop
全屏元素后面的背景层video::backdrop { background: black; }
::marker
(CSS3 新增)
选择列表项的标记(如<li>
的项目符号)li::marker { color: red; }
::spelling-error
(实验性)
标记浏览器检测到的拼写错误文本::spelling-error { text-decoration: wavy red underline; }
::grammar-error
(实验性)
标记浏览器检测到的语法错误文本::grammar-error { text-decoration: wavy green underline; }
注意事项
单冒号 vs 双冒号:
- 单冒号是CSS2的写法,CSS3 规范推荐使用
::
(如::before
) - 但浏览器也支持
:
写法(如:before
)以保持兼容性 - 唯一例外是
:before
、:after
、:first-letter
和:first-line
在 CSS2 中已存在
- 单冒号是CSS2的写法,CSS3 规范推荐使用
必须设置
content
属性:.box::before { content: ""; /* 必须设置,即使是空字符串 */ display: block; width: 20px; }
伪元素组合使用:
blockquote::first-letter::after { content: "'"; color: red; }
浏览器兼容性:
- 大多数现代浏览器支持所有标准伪元素
::marker
在旧浏览器中支持有限::spelling-error
和::grammar-error
仍处于实验阶段
实际应用示例
/* 自定义列表标记 */
ul li::marker {
content: "✓ ";
color: green;
}
/* 输入框清除按钮样式 */
input[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: none;
height: 1em;
width: 1em;
background: url(close.svg) no-repeat;
}
/* 首行首字母特殊样式 */
article p::first-line {
font-variant: small-caps;
}
article p::first-letter {
font-size: 3em;
float: left;
line-height: 1;
}