伪元素(双冒号 ::)对元素的特定部分进行样式设置,或生成不在 HTML 中的内容 — 无需添加额外标记。
::before 和 ::after — 生成的内容
css
.note::before {
content: ;
}
{
: ;
}
content 属性是必需的 — 没有它,伪元素不会呈现。生成的内容是元素开头(::before)或末尾(::after)的一个子元素。
.tooltip::after {
content: ""; /* empty but present → creates a box */
position: absolute;
border: 8px solid transparent;
border-top-color: black; /* a CSS triangle (tooltip arrow) */
}
这是经典用法:绘制箭头、徽章、叠加层、装饰线 — 使 HTML 不含纯粹的视觉元素。
p::first-line { font-weight: bold; } /* the first rendered line */
p::first-letter { font-size: 3em; } /* drop cap */
::selection { background: yellow; } /* highlighted/selected text */
input::placeholder { color: gray; } /* placeholder text */
.x:hover { } /* pseudo-CLASS (state) — one colon */
.x::before { } /* pseudo-ELEMENT (a part) — two colons */
CSS3 引入了 :: 来区分伪元素和伪类(为了兼容性,浏览器仍然接受旧伪元素上的单冒号,但请使用 ::)。
生成的 content 会被某些屏幕阅读器读取 — 不要仅在 ::before/::after 中放入必要信息(将其用于装饰),并且最好将装饰图标排除在无障碍树之外。
伪元素允许你在纯 CSS 中添加图标、装饰形状(箭头、分隔线)、首字下沉和计数器 — 无需额外的 <div>s 或 <span>s。
它们在保持标记语义的同时实现丰富的视觉细节,是简洁、易维护样式的基础。