直观展示标题等级

今日研究了如何让标题的等级更直观展现,在 AI 的帮助下参照 Typora-Vue 主题写了一段 CSS


/* 为所有标题设置相对定位 */
.markdown-preview-view h1,
.markdown-preview-view h2,
.markdown-preview-view h3,
.markdown-preview-view h4,
.markdown-preview-view h5,
.markdown-preview-view h6,
.cm-header-1,
.cm-header-2,
.cm-header-3,
.cm-header-4,
.cm-header-5,
.cm-header-6 {
    position: relative; /* 确保伪元素的定位基于标题 */
}

/* 编辑模式和阅读模式通用的样式 */
[class*="cm-header-"]:not([class*="cm-formatting-header-"])::before,
.markdown-preview-view h1::before,
.markdown-preview-view h2::before,
.markdown-preview-view h3::before,
.markdown-preview-view h4::before,
.markdown-preview-view h5::before,
.markdown-preview-view h6::before {
    content: attr(data-heading); /* 动态显示标题级别 */
    font-size: var(--font-text-size); /* 使用正文字体大小 */
    opacity: 0.3; /* 设置透明度 */
    position: absolute; /* 绝对定位 */
    left: -45px; /* 向左移动45px,避免与收起展开箭头重叠 */
    width: auto; /* 宽度自适应 */
    top: 50%; /* 将标签垂直居中 */
    transform: translateY(-50%); /* 通过偏移实现精确对齐 */
}

/* 编辑模式下的标题标签 */
.cm-header-1:not(.cm-formatting-header-1)::before { content: " H1"; }
.cm-header-2:not(.cm-formatting-header-2)::before { content: " H2"; }
.cm-header-3:not(.cm-formatting-header-3)::before { content: " H3)"; }
.cm-header-4:not(.cm-formatting-header-4)::before { content: " H4"; }
.cm-header-5:not(.cm-formatting-header-5)::before { content: " H5"; }
.cm-header-6:not(.cm-formatting-header-6)::before { content: " H6"; }

/* 阅读模式下的标题标签 */
.markdown-preview-view h1::before { content: " H1"; }
.markdown-preview-view h2::before { content: " H2"; }
.markdown-preview-view h3::before { content: " H3"; }
.markdown-preview-view h4::before { content: " H4"; }
.markdown-preview-view h5::before { content: " H5"; }
.markdown-preview-view h6::before { content: " H6"; }

挺好。之前的也可以看这个帖子 [1.0船新版本 CSS 片段系列] 标题美化 - #13,来自 PlayerMiller

image

更:又看了下,代码几乎一样的。

看样子现在实现类似效果还是普遍使用伪元素。

我是参照 Typora-Vue 主题改的,我个人喜欢无边框并且我希望它不用在悬停状态下才显示,所以我就去找 Deepseek 帮忙改了一下。因为我平常喜欢 Minimal 主题,但是这个主题的不同标题之间字号差别不大,难以区分,虽然可以设置多彩标题但我还是更喜欢单色调的标题。也试过给不同级别的标题设置不同字号,但是要设置六个级别的字号且还要和正文字号区分实在麻烦。偶然间发现 Typora-Vue 主题里的标题悬停效果很合我意,于是就去粘贴复制然后找 AI 魔改了。不过我本来的目的就是为了在编辑和预览状态下直观展示标题等级,所以我就删除了悬停效果。附上 Typora-Vue 的 theme.css 的地址:Obsidian-Typora-Vue-Theme/theme.css at master · ZekunC/Obsidian-Typora-Vue-Theme · GitHub