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

Obsidian中CSS代码无法正确计数图片序号的问题求助

问题

我刚使用Obsidian.md,希望通过HTML制作图片并为标题添加自动序号“Fig. X”,于是编写了一段CSS代码,但所有图片的标题都显示“Fig. 1”。测试发现将图片包裹在<body>标签内可正常计数,但我不想给整个笔记套<body>标签,求问问题原因及解决办法。

原CSS代码

<style>
    /* initialise the counter */
    body { counter-reset: figureCounter; }
    /* increment the counter for every instance of a figure even if it doesn't have a caption */
    figure { counter-increment: figureCounter; }
    /* prepend the counter to the figcaption content */
    figure figcaption:before {
        content: "Fig " counter(figureCounter) ": "
    }
</style>

测试用HTML代码(包裹<body>可正常计数)

<body>
  <figure>
    <img src = "link" width = 250>
    <figcaption>This is the caption</figcaption>
  </figure>
  <figure>
    <img src = "link" width = 250>
    <figcaption>This is the caption</figcaption>
  </figure>
</body>

问题原因

你的CSS将计数器figureCounter的初始化规则绑定在了<body>元素上,但在Obsidian中,单条笔记的内容并非直接挂载在<body>标签下,而是被包裹在Obsidian自带的专属容器(如.markdown-preview-view这类预览容器)中。

当你不在笔记里手动添加<body>标签时,counter-reset: figureCounter规则找不到生效的<body>元素,导致计数器无法在统一的上下文里初始化;每条<figure>会默认在各自的局部环境中重新触发计数器,所以序号始终停留在“Fig. 1”。而手动添加<body>后,所有<figure>都处于同一个<body>的上下文中,计数器能被正确共享和递增。


解决办法

方法1:适配Obsidian自带容器初始化计数器

直接将计数器初始化绑定到Obsidian的笔记容器上,无需手动添加<body>标签,同一条笔记内的所有<figure>会自动共享计数器:

<style>
    /* 针对预览模式容器初始化计数器 */
    .markdown-preview-view { counter-reset: figureCounter; }
    /* 若需要在编辑模式也生效,添加这条 */
    .markdown-source-view { counter-reset: figureCounter; }
    
    figure { counter-increment: figureCounter; }
    figure figcaption:before {
        content: "Fig " counter(figureCounter) ": "
    }
</style>

方法2:自定义父容器绑定计数器

如果不想依赖Obsidian的容器类名,可以给笔记内的<figure>套一个自定义父容器,将计数器初始化绑定到这个容器上:
修改后的CSS:

<style>
    .figure-group { counter-reset: figureCounter; }
    figure { counter-increment: figureCounter; }
    figure figcaption:before {
        content: "Fig " counter(figureCounter) ": "
    }
</style>

笔记中的HTML写法:

<div class="figure-group">
  <figure>
    <img src="link" width="250">
    <figcaption>This is the caption</figcaption>
  </figure>
  <figure>
    <img src="link" width="250">
    <figcaption>This is the caption</figcaption>
  </figure>
</div>

这种方式更灵活,即使Obsidian的容器类名变化也不会受影响,且只需给目标图片组套一个轻量容器即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:52:49