CSS Content 属性作用

CSS content 属性的用法和常见应用场景

问题

CSS 属性 content 有什么作用?

解答

content 属性用于在元素的 ::before::after 伪元素中插入生成内容。它是伪元素生效的必要属性。

基本用法

/* 插入文本 */
.tip::before {
  content: "提示:";
  color: #f60;
}

/* 空内容(常用于装饰) */
.icon::before {
  content: "";
  display: inline-block;
  width: 16px;
  height: 16px;
  background: url("icon.png");
}

插入属性值

<a href="https://example.com">链接</a>
/* 使用 attr() 获取元素属性 */
a::after {
  content: " (" attr(href) ")";
  color: #999;
  font-size: 12px;
}
/* 渲染结果:链接 (https://example.com) */

计数器

/* 自动编号 */
ol {
  counter-reset: item; /* 初始化计数器 */
}

li::before {
  counter-increment: item; /* 递增计数器 */
  content: counter(item) ". "; /* 显示计数器 */
}

插入引号

q {
  quotes: "「" "」"; /* 定义引号样式 */
}

q::before {
  content: open-quote;
}

q::after {
  content: close-quote;
}

清除浮动

/* 经典 clearfix */
.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

content 的值类型

说明
"string"插入文本字符串
url()插入图片
attr()插入元素属性值
counter()插入计数器
open-quote / close-quote插入引号
none不生成内容
normal默认值,伪元素不生成

关键点

  • content::before::after 伪元素必需的属性,没有它伪元素不会渲染
  • 即使不需要内容,也要写 content: ""
  • attr() 可以动态获取 HTML 属性值
  • 生成的内容不在 DOM 中,无法被选中或复制
  • 不要用 content 插入重要内容,屏幕阅读器可能无法识别