Hexo Matery 代码显示问题排查与修复


问题现象

阿巴阿巴终于有时间解决一些博客外观的遗留问题。之前写着写着博客突然发现我博文的代码显示有点 Bug,主要这两点:

  • 代码块被拆成左右分栏。
  • 函数名/类名被莫名加粗,像是标题样式。

具体呈现 belike:

图1 代码分栏 图2 异常加粗

根因与思路

分栏问题的本质是:有些代码横向宽度太窄,被识别边界后不足正文横宽,显示出分栏的样子。解决思路:

  1. 短代码:让显示黑框自动包裹内容并居中。
  2. 长代码:限制最大宽度,超过时横向滚动。

直接在themes\matery\source\css\my.css最后加入代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* ========== 修正:短代码居中,长代码限制宽度并滚动 ========== */

figure.highlight {
/* 1. 核心逻辑:尽可能包裹内容,但绝不超过父容器宽度 */
width: fit-content !important;
max-width: 100% !important; /* 关键:限制最大宽度为文章宽度,防止撑破 */

/* 2. 居中显示 */
margin: 1.5rem auto !important;
display: block !important;

/* 3. 滚动机制:当内容超过 max-width 时,显示横向滚动条 */
overflow-x: auto !important;

/* 4. 美观调整:给极短的代码设一个最小宽度,避免看起来太小气 */
min-width: 50%;
border-radius: 10px; /* 保持圆角 */
}

/* 确保内部表格正确填充 */
figure.highlight table {
width: 100% !important;
display: table !important;
table-layout: auto !important;
}

/* 保持内部代码不换行,强制触发滚动条 */
figure.highlight pre {
white-space: pre !important;
word-wrap: normal !important;
word-break: normal !important;
}

/* 针对移动端优化:手机屏幕窄,直接强制100%宽,避免两边留白太丑 */
@media (max-width: 768px) {
figure.highlight {
width: 100% !important;
min-width: 100% !important;
}
}

函数名/类名加粗的问题则是样式冲突。

我使用的 Hexo Matery 主题底层依赖于 Materialize.css 框架,代码块里的函数名继承了 UI 框架里的大标题样式,导致它们看起来像是一个网页标题,而不是代码。

解决方法就是在 my.css 中强制指定代码块里面的 .title:不要用大字体而是跟随代码原本的大小。

直接在themes\matery\source\css\my.css最后加入代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* ========== 修正:解决代码块中函数名/类名变成了大标题字体的问题 ========== */

/* 强制重置代码块内部所有 span 标签的字体大小和行高 */
figure.highlight pre .title,
figure.highlight pre .function,
figure.highlight pre .class,
figure.highlight pre .params {
font-size: inherit !important; /* 继承父元素(代码块)的大小,而不是用标题大小 */
font-family: inherit !important; /* 强制使用代码字体 */
line-height: inherit !important; /* 修复行高 */
font-weight: bold !important; /* 保持加粗(如果不喜欢加粗,可以改成 normal) */
margin: 0 !important; /* 去除可能存在的标题外边距 */
}

/* 额外保险:防止某些特定高亮主题使用了 span 标签的通用样式 */
figure.highlight span {
font-size: 100% !important;
}

此外,我还发现自己原来下载了两套代码渲染,最后选用了原来内置的prism,卸载了prism_plugin

最后开启代码行数显示,这两步主要是改动主题下的_config.yml

最终代码正常显示。

图3 主题_config.yml设置 图4 完成修改

👉 点击这里继续阅读:《博客版权声明与图片水印方案》


Author: linda1729
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source linda1729 !
评论
  TOC