使用MCP定位并修复 MathJax 公式字号样式不生效

最近想给博客里的数学公式统一字体和字号,于是新增了 source/custom/math/math.css 并在 _config.fluid.ymlcustom_css 引入。但实际预览(http://localhost:4000/)时发现:CSS 明明加载了,字号却没有变化。

这篇优化日记记录一次用 Codex CLI + MCP chrome-devtools 的定位过程,并给出最终可长期维护的修复方案。

现象

  • 文章页(例如《自动编号与定位测试》)MathJax 渲染正常
  • math.css 在页面 <head> 中确实被引入(Elements / Network 都能看到)
  • 但我在 math.css 里写的 mjx-container { font-size: ... } 并没有改变公式字号

用 MCP 在浏览器里定位

打开文章页:

  • http://localhost:4000/2025/12/18/2025-12-18-自动编号与定位测试/

在 DevTools 里检查任意一个公式节点,会看到类似结构:

  • <mjx-container jax="CHTML" display="true" ...>
  • 且它带有内联样式(inline style),例如:style="font-size: 113.1%; ..."

根因:内联 style 的优先级更高

MathJax v3(CHTML 输出)会给 <mjx-container> 写入内联 font-size 做缩放与布局。浏览器优先级规则是:

  • 内联样式 style="..." > 普通 CSS 选择器

所以如果我们只是写:

1
mjx-container[display="true"] { font-size: 1.10rem; }

会被 MathJax 的内联 font-size: 113.1% 压过去,表现为“没变化”。

修复:对字号使用 !important,并用变量集中控制

我将 source/custom/math/math.css 重写为:

  1. 用 CSS 变量统一管理字体与字号
  2. font-size 规则加 !important,覆盖 MathJax 内联样式
  3. 选择器加上 jax="CHTML".mjx-container 兼容写法

关键片段:

1
2
3
4
5
6
7
8
9
10
11
12
13
:root {
--math-font-family: "STIX Two Math", "Cambria Math", "Times New Roman", "Noto Serif", "STSong", serif;
--math-display-size: 1.10rem;
--math-inline-size: 1.00rem;
}

mjx-container[jax="CHTML"][display="true"] {
font-size: var(--math-display-size) !important;
}

mjx-container[jax="CHTML"]:not([display="true"]) {
font-size: var(--math-inline-size) !important;
}

以后只需要改三个变量,就能快速微调公式字体与大小。

验证

  • 修改 source/custom/math/math.css 后,浏览器 Ctrl+Shift+R 强制刷新
  • 在 DevTools 的 Computed 里看 mjx-containerfont-size,应来自 math.css 规则(而不是内联 style)

相关文件

  • CSS:source/custom/math/math.css
  • 引用:_config.fluid.ymlcustom_css 引入 /custom/math/math.css
  • 测试文章:source/_posts/2025-12-18-自动编号与定位测试.md(Front-matter math: true

使用MCP定位并修复 MathJax 公式字号样式不生效
http://sakura.lsk.icu/2025/12/20/优化日记/3.mathjax-formula-font-size-fix/
作者
Sakura
发布于
2025年12月20日
许可协议