You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使CSS标题计数器在存在或不存在h1元素时均生效?

解决CSS标题自动计数的场景适配问题

一、CSS可以实现分场景逻辑

通过:has()伪类就能检测页面中是否存在h1元素,从而切换不同的计数规则。之前尝试失败大概率是写法有误,或者你的笔记应用对:has()的兼容性不足(需要基于Chromium 101+、Firefox 121+这类较新的内核版本)。

二、两种需求场景的实现代码

场景1:无h1时h2显示为1.,h3显示为1.1.

/* 初始化计数器 */
body {
  counter-reset: h1-counter h2-counter h3-counter;
}

/* 有h1时的计数规则(保留你原本正常工作的逻辑) */
body:has(h1) h1 {
  counter-increment: h1-counter;
  counter-reset: h2-counter;
}
body:has(h1) h2 {
  counter-increment: h2-counter;
  counter-reset: h3-counter;
}
body:has(h1) h3 {
  counter-increment: h3-counter;
}
body:has(h1) h1::before {
  content: counter(h1-counter) ". ";
}
body:has(h1) h2::before {
  content: counter(h1-counter) "." counter(h2-counter) ". ";
}
body:has(h1) h3::before {
  content: counter(h1-counter) "." counter(h2-counter) "." counter(h3-counter) ". ";
}

/* 无h1时的计数规则 */
body:not(:has(h1)) h2 {
  counter-increment: h1-counter; /* 复用h1计数器让h2从1开始 */
  counter-reset: h2-counter;
}
body:not(:has(h1)) h3 {
  counter-increment: h2-counter;
}
body:not(:has(h1)) h2::before {
  content: counter(h1-counter) ". ";
}
body:not(:has(h1)) h3::before {
  content: counter(h1-counter) "." counter(h2-counter) ". ";
}

场景2:无h1时h2显示为1.1.,h3显示为1.1.1.

/* 初始化计数器 */
body {
  counter-reset: h1-counter h2-counter h3-counter;
}

/* 有h1时的计数规则(保留原逻辑) */
body:has(h1) h1 {
  counter-increment: h1-counter;
  counter-reset: h2-counter;
}
body:has(h1) h2 {
  counter-increment: h2-counter;
  counter-reset: h3-counter;
}
body:has(h1) h3 {
  counter-increment: h3-counter;
}
body:has(h1) h1::before {
  content: counter(h1-counter) ". ";
}
body:has(h1) h2::before {
  content: counter(h1-counter) "." counter(h2-counter) ". ";
}
body:has(h1) h3::before {
  content: counter(h1-counter) "." counter(h2-counter) "." counter(h3-counter) ". ";
}

/* 无h1时的计数规则 */
body:not(:has(h1)) {
  counter-reset: h1-counter 1; /* 预设h1计数器为1,直接作为一级前缀 */
}
body:not(:has(h1)) h2 {
  counter-increment: h2-counter;
  counter-reset: h3-counter;
}
body:not(:has(h1)) h3 {
  counter-increment: h3-counter;
}
body:not(:has(h1)) h2::before {
  content: counter(h1-counter) "." counter(h2-counter) ". ";
}
body:not(:has(h1)) h3::before {
  content: counter(h1-counter) "." counter(h2-counter) "." counter(h3-counter) ". ";
}

三、:has()不生效的兼容方案

如果你的笔记应用内核版本较低,不支持:has(),可以手动给body加类来区分:

  • 当页面有h1时,给body添加has-h1类;无h1时不加
  • 把代码里的body:has(h1)替换成body.has-h1,body:not(:has(h1))替换成body:not(.has-h1)即可

内容的提问来源于stack exchange,提问作者hardfork

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 03:43:13