⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

CSS 伪元素

学习 ::before/::after/::first-line/::selection · 难度:进阶 · +15XP

CSS 伪元素完全指南

伪元素(Pseudo-elements)允许你为元素的特定部分设置样式,或者创建虚拟的额外元素而无需修改 HTML 结构。它们是 CSS 中最强大的特性之一。

常用伪元素一览

伪元素语法作用
::beforep::before在元素内容之前插入内容
::afterp::after在元素内容之后插入内容
::first-linep::first-line选中文本首行
::first-letterp::first-letter选中文本首字
::selection::selection用户选中的文本部分
::placeholderinput::placeholder表单占位文字
::markerli::marker列表项标记

::before 和 ::after

这两个是最常用的伪元素,必须配合 content 属性使用

/* 基本用法 — 添加装饰内容 */
.quote::before {
  content: '"';
  font-size: 3em;
  color: #ccc;
  line-height: 0;
  vertical-align: middle;
}

.quote::after { content: '"'; font-size: 3em; color: #ccc; vertical-align: middle; }

清除浮动(经典用法)

.clearfix::after {
  content: '';
  display: table;
  clear: both;
}

自定义列表标记

li::marker {
  color: #2196F3;
  font-size: 1.2em;
  content: '>';
}

首字下沉效果

article p:first-of-type::first-letter {
  float: left;
  font-size: 4em;
  line-height: 0.8;
  font-weight: bold;
  margin-right: 8px;
  color: #c0392b;
  font-family: Georgia, serif;
}

自定义选中颜色

::selection {
  background: #ffeb3b;
  color: #333;
}

/* 特定元素 */ .highlight::selection { background: #e91e63; color: white; }

复杂装饰 — 引号徽章

.badge {
  position: relative;
  display: inline-block;
  padding: 6px 12px;
  background: #4CAF50;
  color: white;
}

.badge::after { content: attr(data-count); /* 使用自定义属性 */ position: absolute; top: -8px; right: -8px; background: red; color: white; border-radius: 50%; width: 20px; height: 20px; font-size: 12px; display: flex; align-items: center; justify-content: center; }

注意事项

  1. ::before::after 必须有 content 属性,即使为空也要写 content: ''
  2. 伪元素默认是 inline 元素,需要设置 display 来改变
  3. 伪元素不属于 DOM,无法通过 JavaScript 直接操作
  4. CSS3 规范使用双冒号 ::,CSS2 使用单冒号 :,建议使用双冒号
  5. 一个选择器最多只能有一个 ::before 和一个 ::after
  6. ::first-line 只对块级元素有效

伪元素是 CSS 中极具创造力的工具。通过巧妙运用伪元素,你可以在不增加 HTML 标签的情况下实现丰富的视觉效果,保持代码简洁。

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 122 篇
0 完成
🔥 0