CSS content 属性用法

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

问题

CSS 的 content 属性有什么作用?有哪些应用场景?

解答

content 属性用于在元素的 ::before::after 伪元素中插入内容。这些内容是纯装饰性的,不会出现在 DOM 中,也不会被搜索引擎抓取。

基本语法

/* 插入文本 */
.text::before {
  content: "前缀";
}

/* 插入空内容(常用于清除浮动或创建装饰元素) */
.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

/* 插入图片 */
.icon::before {
  content: url("icon.png");
}

/* 插入属性值 */
a::after {
  content: attr(href);
}

/* 插入引号 */
q::before {
  content: open-quote;
}
q::after {
  content: close-quote;
}

/* 插入计数器 */
li::before {
  content: counter(item) ". ";
  counter-increment: item;
}

应用场景

1. 清除浮动

.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

2. 添加图标

/* 外链图标 */
a[href^="http"]::after {
  content: " ↗";
}

/* 必填标记 */
.required::after {
  content: "*";
  color: red;
}

3. 显示链接地址(打印样式)

@media print {
  a[href]::after {
    content: " (" attr(href) ")";
  }
}

4. 自定义列表序号

ol {
  counter-reset: item;
  list-style: none;
}

ol li::before {
  content: counter(item) "、";
  counter-increment: item;
  color: #666;
}

5. 装饰性元素

/* 分隔线 */
.divider::before,
.divider::after {
  content: "";
  flex: 1;
  height: 1px;
  background: #ddd;
}

/* 引用样式 */
blockquote::before {
  content: """;
  font-size: 3em;
  color: #ccc;
}

6. 面包屑分隔符

.breadcrumb li:not(:last-child)::after {
  content: " / ";
  color: #999;
}

完整示例

<!DOCTYPE html>
<html>
<head>
  <style>
    /* 必填标记 */
    .required::after {
      content: " *";
      color: red;
    }

    /* 外链标记 */
    a[target="_blank"]::after {
      content: " ↗";
      font-size: 0.8em;
    }

    /* 自定义计数器 */
    .custom-list {
      counter-reset: step;
      list-style: none;
      padding: 0;
    }

    .custom-list li {
      counter-increment: step;
      margin: 10px 0;
    }

    .custom-list li::before {
      content: "Step " counter(step) ": ";
      font-weight: bold;
      color: #007bff;
    }

    /* tooltip 显示 data 属性 */
    .tooltip {
      position: relative;
      cursor: help;
      border-bottom: 1px dashed #666;
    }

    .tooltip:hover::after {
      content: attr(data-tip);
      position: absolute;
      bottom: 100%;
      left: 0;
      background: #333;
      color: #fff;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      white-space: nowrap;
    }
  </style>
</head>
<body>
  <label class="required">用户名</label>
  <br><br>
  
  <a href="https://example.com" target="_blank">外部链接</a>
  <br><br>
  
  <ol class="custom-list">
    <li>安装依赖</li>
    <li>配置环境</li>
    <li>启动项目</li>
  </ol>
  
  <p>
    这是一个
    <span class="tooltip" data-tip="这是提示内容">带提示的文字</span>
  </p>
</body>
</html>

关键点

  • content 只能用于 ::before::after 伪元素
  • 插入的内容是装饰性的,不在 DOM 中,无法被选中或复制
  • attr() 可以读取元素属性值,常用于显示 hrefdata-*
  • counter() 配合 counter-resetcounter-increment 实现自定义计数
  • content: "" 常用于清除浮动或创建纯装饰性元素