一、核心概念区分
伪类(Pseudo-classes)
作用:选择元素的特定状态
语法:单冒号 :
示例::hover, :focus, :first-child
伪元素(Pseudo-elements)
作用:创建元素的虚拟子元素
语法:双冒号 ::(CSS3规范,单冒号仍兼容)
示例:::before, ::after, ::first-line
二、常用伪类详解
- 状态伪类
css
/* 链接相关 */
a:link { color: blue; } /* 未访问链接 */
a:visited { color: purple; } /* 已访问链接 */
a:hover { color: red; } /* 鼠标悬停 */
a:active { color: orange; } /* 激活状态(点击时) */
a:focus { outline: 2px solid blue; } /* 获得焦点 */
/* 表单相关 */
input:disabled { opacity: 0.5; }
input:enabled { opacity: 1; }
input:checked { background: green; }
input:required { border-color: red; }
input:invalid { border-color: #f00; }
input:valid { border-color: #0f0; }
- 结构伪类
css
/* 基础选择 */
:first-child { color: red; }
:last-child { color: blue; }
:only-child { font-weight: bold; }
/* 位置选择 */
:nth-child(2) { background: yellow; }
:nth-child(odd) { background: #f5f5f5; } /* 奇数 */
:nth-child(even) { background: #eee; } /* 偶数 */
:nth-child(3n) { color: green; } /* 3的倍数 */
:nth-child(3n+1) { color: red; } /* 3n+1 */
:nth-last-child(2) { opacity: 0.8; } /* 倒数第二个 */
/* 类型选择 */
p:first-of-type { font-size: 1.2em; }
p:last-of-type { border-bottom: 1px solid #ccc; }
:nth-of-type(2n) { margin-left: 20px; }
:only-of-type { text-align: center; }
/* 空元素 */
div:empty { display: none; }
- 其他伪类
css
/* 否定伪类 */
:not(p) { margin: 0; }
:not(.exclude) { color: #333; }
/* 目标伪类(URL锚点) */
#section1:target { background: #ffeb3b; }
/* 根元素 */
:root { --main-color: #3498db; }
/* 全屏伪类 */
video:fullscreen { width: 100%; }
/* 语言选择 */
:lang(en) { quotes: '"' '"'; }
:lang(fr) { quotes: '<<' '>>'; }
三、常用伪元素详解
- 内容生成
css
/* ::before 和 ::after */
.element::before {
content: "前缀 - ";
color: #999;
}
.element::after {
content: " (后缀)";
font-size: 0.8em;
color: #666;
}
/* 实用案例 */
.icon::before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
background: url(icon.svg);
margin-right: 5px;
}
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
background: #333;
color: white;
padding: 5px;
border-radius: 3px;
white-space: nowrap;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover::after {
opacity: 1;
}
- 文本修饰
css
/* 首行 */
p::first-line {
font-weight: bold;
color: #333;
}
/* 首字母 */
p::first-letter {
font-size: 2em;
float: left;
line-height: 1;
margin-right: 5px;
}
/* 选中文本 */
::selection {
background: #ffeb3b;
color: #000;
}
::-moz-selection { /* Firefox */
background: #ffeb3b;
color: #000;
}
/* 占位符文本 */
input::placeholder {
color: #aaa;
font-style: italic;
}
- 列表与表单
css
/* 列表标记 */
li::marker {
color: red;
content: "▶ ";
}
/* 输入框文件按钮 */
input[type="file"]::file-selector-button {
background: #4CAF50;
color: white;
padding: 8px 12px;
border: none;
border-radius: 4px;
}
伪类和伪元素的区别?
伪类选择状态,伪元素创建虚拟元素
语法不同(: 和 ::)
伪元素可以插入内容
:nth-child 和 :nth-of-type 的区别?
:nth-child 在所有子元素中计数
:nth-of-type 在同类型元素中计数
::before 和 ::after 的 content 属性必填吗?
除了 content: "" 空字符串外,必须设置 content
空 content 可用于布局目的
哪些伪元素不能和 ::before/::after 组合使用?
替换元素(img、input、video等)不支持
单标记元素(br、hr等)通常不支持