⚡ 编程实验室🏗️ 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 伪类选择器

CSS 伪类和伪元素 · 难度:进阶 · +15XP

CSS 伪类和伪元素

CSS 伪类(Pseudo-classes)和伪元素(Pseudo-elements)用于选择元素的特殊状态特定部分。它们让你无需修改 HTML 就能实现丰富的交互效果和精细节样式控制。

伪类(:)—— 选择元素状态

伪类用于定义元素的特殊状态。一个冒号(:)为前缀。

/* 链接状态伪类 */
a:link    { color: blue; }      /* 未访问 */
a:visited { color: purple; }    /* 已访问 */
a:hover   { color: red; }       /* 悬停 */
a:active  { color: orange; }    /* 点击时 */

/* 输入框状态 */ input:focus { border-color: #3498db; outline: none; } input:disabled { background: #f0f0f0; cursor: not-allowed; } input:checked { accent-color: #3498db; } input:invalid { border-color: red; }

/* 结构伪类 */ li:first-child { font-weight: bold; } /* 第一个子元素 */ li:last-child { border-bottom: none; } /* 最后一个 */ li:nth-child(odd) { background: #f9f9f9; } /* 奇数行 */ li:nth-child(even) { background: #fff; } /* 偶数行 */ li:nth-child(3) { color: red; } /* 第 3 个 */ li:nth-child(3n) { border-left: 3px solid blue; } /* 每 3 个 */

伪元素(::)—— 创建虚拟元素

伪元素用于样式化元素的特定部分插入内容。两个冒号(::)为前缀。

/* ::before 和 ::after —— 在元素前后插入内容 */
.quote::before {
  content: "\201C";  /* 左双引号 */
  font-size: 2em;
  color: #3498db;
}
.quote::after {
  content: "\201D";  /* 右双引号 */
  font-size: 2em;
  color: #3498db;
}

/* ::first-line —— 首行 */ p::first-line { font-weight: bold; color: #2c3e50; }

/* ::first-letter —— 首字母 */ p::first-letter { font-size: 3em; float: left; margin-right: 5px; color: #e74c3c; }

/* ::selection —— 用户选中文本 */ ::selection { background: #ffeaa7; color: #2d3436; }

/* ::placeholder —— 输入框占位文本 */ input::placeholder { color: #b2bec3; font-style: italic; }

常见伪类速查表

伪类作用示例
:hover鼠标悬停a:hover { color: red; }
:focus获得焦点input:focus { outline: blue; }
:first-child第一个子元素li:first-child { }
:last-child最后一个子元素li:last-child { }
:nth-child(n)第 n 个子元素tr:nth-child(even)
:not(selector)排除选择器li:not(.active) { }
:checked选中状态input:checked { }
:disabled禁用状态input:disabled { }
:empty空元素div:empty { display: none; }

???? 练习

  1. 用 :hover 和 :focus 美化链接、按钮和输入框的交互状态
  2. 使用 ::before 和 ::after 为引用块添加装饰性引号
  3. 用 ::first-letter 创建杂志风格的首字下沉效果
  4. 使用 :nth-child(odd) 和 :nth-child(even) 制作斑马条纹表格
  5. 用 ::selection 自定义网页文字选中时的背景色

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

🏆 学习排行

加载中...

📊 统计

📖 122 篇
0 完成
🔥 0