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

如何实现Jupyter Notebook中编号后Markdown标题文本左对齐?

解决方法

由于Jupyter Notebook中不同层级Markdown标题的字体大小存在差异,使用空格字符( / )无法保证文本起始位置对齐,推荐以下几种可行方案:

方案1:HTML标题+固定宽度内联元素

给每个标题的编号部分套一个固定宽度的span标签,无论字体大小,编号区域都会占用相同宽度,后续文本自然对齐。

示例代码:

<h2><span style="display: inline-block; width: 40px;">1.</span> heading1</h2>
<h3><span style="display: inline-block; width: 40px;">1.1</span> subheading1</h3>
<h3><span style="display: inline-block; width: 40px;">1.2</span> subheading2</h3>
<h4><span style="display: inline-block; width: 40px;">1.2.1</span> subsubheading1</h4>
<h2><span style="display: inline-block; width: 40px;">2.</span> heading2</h2>
<h3><span style="display: inline-block; width: 40px;">2.1</span> subheading1</h3>

可根据编号长度(比如10.1.1这类长编号)调整width值,确保编号完全容纳且不占用额外空间。

方案2:自定义全局CSS(批量处理)

如果需要对齐大量标题,可修改Jupyter的自定义CSS,避免重复编写内联样式:

  1. 找到Jupyter配置目录(通常为~/.jupyter/custom/)
  2. 创建或编辑custom.css文件,添加以下样式:
.align-heading .num {
    display: inline-block;
    width: 40px;
}
  1. 在Markdown中使用带类的HTML标题:
<h2 class="align-heading"><span class="num">1.</span> heading1</h2>
<h3 class="align-heading"><span class="num">1.1</span> subheading1</h3>

方案3:无边框表格布局

用表格将编号和文本分离,隐藏边框后可实现完美对齐,还能自定义字体样式:

<table style="border-collapse: collapse; width: 100%;">
    <tr>
        <td style="border: none; width: 50px;">1.</td>
        <td style="border: none; font-size: 1.5em; font-weight: bold;">heading1</td>
    </tr>
    <tr>
        <td style="border: none; width: 50px;">1.1</td>
        <td style="border: none; font-size: 1.25em; font-weight: bold;">subsubheading1</td>
    </tr>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:17:35