伪类和伪元素的区别?常见的有哪些?
区别
- 伪类(:):选择处于特定状态的元素,单冒号
- 伪元素(::):创建不存在于 DOM 的虚拟元素,双冒号
常见伪类
交互状态:
:hover /* 鼠标悬停 */
:active /* 点击瞬间 */
:focus /* 获得焦点 */
:focus-visible /* 键盘获得焦点(区分鼠标/键盘) */
:visited /* 已访问的链接 */结构选择:
:first-child /* 第一个子元素 */
:last-child /* 最后一个子元素 */
:nth-child(n) /* 第 n 个 */
:nth-child(odd) /* 奇数 */
:nth-child(even) /* 偶数 */
:nth-of-type(n) /* 同类型第 n 个 */
:only-child /* 唯一子元素 */
:not(selector) /* 不匹配的 */
:empty /* 没有子元素 */表单伪类:
:checked /* 选中的复选框/单选 */
:disabled /* 禁用的表单元素 */
:valid /* 通过验证 */
:invalid /* 未通过验证 */
:placeholder-shown /* 正在显示 placeholder */常见伪元素
::before /* 元素内容前插入 */
::after /* 元素内容后插入 */
::first-letter /* 首字母 */
::first-line /* 首行 */
::selection /* 选中的文字 */
::placeholder /* placeholder 样式 */
::marker /* 列表标记 */::before / ::after 使用示例
/* 清除浮动 */
.clearfix::after {
content: '';
display: block;
clear: both;
}
/* 自定义引号 */
.quote::before { content: '“'; } /* 左引号 */
.quote::after { content: '”'; } /* 右引号 */
/* 工具提示 */
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
background: black;
color: white;
padding: 4px 8px;
border-radius: 4px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover::after { opacity: 1; }
/* 装饰性图标 */
.icon::before {
content: '';
display: inline-block;
width: 16px;
height: 16px;
background: url('icon.svg');
}关键点
- 伪元素必须设置
content属性才能显示 - 伪元素默认是
inline,可修改display - 伪类选择的是真实存在的元素,伪元素创建的是虚拟元素
- CSS3 规范伪元素用双冒号
::,但浏览器也兼容单冒号