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

在GitHub Pages的Jekyll站点加载MathJax且不覆盖原有布局

问题:GitHub Pages(Jekyll)加载MathJax后丢失默认样式

我搭建了一个基于Jekyll的GitHub Pages站点,需要加载MathJax渲染数学内容,但添加自定义布局后,页面丢失了原有样式,不过数学公式可以正常渲染。

站点信息

根目录结构

.
├── README.md
├── _config.yml
├── _layouts
│   └── default.html
├── hamiltonian
│   └── some_content.md
└── learning
    └── some_content.md

未使用自定义布局时的_config.yml配置

plugins:
  - jekyll-relative-links
relative_links:
  enabled: true
  collections: true
include:
  - README.md

此时站点未安装主题,GitHub会自动使用默认样式表(normalize.css),样式正常但无法渲染数学内容。

添加自定义布局后的配置与代码

在_config.yml中添加默认布局配置:

defaults:
  -
    scope:
      path: "" # 空字符串表示项目中所有文件
    values:
      layout: "default"

自定义的_layouts/default.html内容:

<!doctype html>
<html lang="en">
<head>
  <!-- inline config -->
  <script>
    MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
        macros: {
         RR: "{\\bf R}",
         bold: ["{\\bf #1}", 1],
         indep: "{\\perp \\!\\!\\! \\perp}",
       }
     },
     svg: {
      fontCache: 'global'
    },
  };
  </script>

  <!-- load MathJax -->
  <script type="text/javascript" id="MathJax-script" async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
  </script>

</head>
<body>
  {{content}}
</body>
</html>

现在数学公式可以正常渲染,但页面丢失了所有样式,需要解决如何在加载MathJax的同时保留原有布局。


解决方案

问题出在自定义的default.html完全替代了GitHub Pages默认的布局结构与样式引用。默认布局不仅包含内容渲染,还引入了normalize.css以及基础排版样式,自定义布局需要把这些元素补回来:

修改_layouts/default.html,添加默认样式引用和页面容器结构:

<!doctype html>
<html lang="en">
<head>
  <!-- 引入默认样式表 -->
  <link rel="stylesheet" href="https://necolas.github.io/normalize.css/8.0.1/normalize.css">
  <!-- 添加GitHub Pages默认的基础排版样式 -->
  <style>
    .markdown-body {
      box-sizing: border-box;
      min-width: 200px;
      max-width: 980px;
      margin: 0 auto;
      padding: 45px;
    }
    @media (max-width: 767px) {
      .markdown-body {
        padding: 15px;
      }
    }
  </style>

  <!-- MathJax配置 -->
  <script>
    MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
        macros: {
         RR: "{\\bf R}",
         bold: ["{\\bf #1}", 1],
         indep: "{\\perp \\!\\!\\! \\perp}",
       }
     },
     svg: {
      fontCache: 'global'
    },
  };
  </script>

  <!-- 加载MathJax -->
  <script type="text/javascript" id="MathJax-script" async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
  </script>

</head>
<body>
  <!-- 用markdown-body容器包裹内容,保持原有排版 -->
  <div class="markdown-body">
    {{ content }}
  </div>
</body>
</html>

这样修改后,既保留了GitHub Pages的默认样式与布局结构,又能正常加载MathJax渲染数学公式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:00:28