代码块居中需按类型选择方案:pre用外层div+margin:0 auto并设width;inline code用text-align:center或display:block+margin;flex布局适合响应式场景;绝对定位适用于悬浮预览。

代码块(<pre class="brush:php;toolbar:false;"></pre> 或 <code>)在技术文档页面中居中,不是简单加 text-align: center 就能生效——它会把内部的缩进、换行、空格全打乱,甚至让语法高亮错位。真正可靠的做法取决于你用的是纯文本 <pre class="brush:php;toolbar:false;"></pre> 还是带语法高亮的内联 <code>,以及是否需要保留原始格式。
pre 标签水平居中:包裹一层 div + margin: 0 auto
<pre class="brush:php;toolbar:false;"></pre> 是块级元素,默认独占一行,且默认不换行、保留空格和缩进。直接对它设 text-align: center 没用;设 margin: 0 auto 又无效,因为它的宽度默认是“内容撑开”,没有固定宽度。
- 必须给
<pre class="brush:php;toolbar:false;"></pre> 显式设置 width(比如 max-width: 800px),否则 margin: 0 auto 不触发
- 更稳妥的做法是用一个外层
<div> 包裹 <code><pre class="brush:php;toolbar:false;"></pre>,然后对该 <div> 设 <code>margin: 0 auto 和 width
- 别忘了重置
<pre class="brush:php;toolbar:false;"></pre> 的默认 margin,否则上下边距会干扰居中效果
示例:
<div style="width: 90%; max-width: 800px; margin: 1em auto;">
<pre class="brush:php;toolbar:false;" style="margin: 0; background: #f4f4f4; padding: 1rem; overflow-x: auto;">
function hello() {
console.log("Hello, world");
}
inline code 标签居中:text-align: center + display: block
像 <code>console.log() 这种内联代码片段,本身是 inline 元素,margin: 0 auto 无效,text-align: center 只对父容器生效——但前提是父容器得是块级,且该 <code> 没被其他样式(如 float 或 display: inline-block)干扰。
- 最简方案:把
<code> 放在段落里,给 <p></p> 加 text-align: center
- 如果要单独居中一行短代码(比如命令行指令),可临时设
display: block 再配 margin: 0 auto
- 注意:设
display: block 后,<code> 会独占一行,但不再继承父级行高,需手动调 line-height 或 padding
示例:
<p style="text-align: center;">
<code>npm install --save-dev vite</code>
</p>
<code style="display: block; margin: 0.5em auto; padding: 0.25em 0.5em; background: #eee;">git commit -m "feat: add docs"</code>
Flex 居中 pre/code:适合响应式文档布局
现代技术文档(如 VuePress、Docusaurus)常用 Flex 布局统一控制区块对齐。对 <pre class="brush:php;toolbar:false;"></pre> 或包裹它的容器用 Flex,好处是不用算宽度,还能同时控制垂直对齐(比如居中在卡片里)。
- 父容器必须设
display: flex,且有明确高度(或最小高度)才能让 align-items: center 生效
- 若只想要水平居中,
justify-content: center 足够;若还要垂直居中(比如模态框里的代码块),再加 align-items: center
- ⚠️ 避免直接对
<pre class="brush:php;toolbar:false;"></pre> 设 display: flex —— 它会破坏 white-space: pre 行为,导致换行失效
示例(居中在固定高卡片中):
<div style="height: 300px; display: flex; justify-content: center; align-items: center; border: 1px solid #ddd;">
<pre class="brush:php;toolbar:false;" style="margin: 0; font-size: 0.9em;">curl -X GET https://api.example.com/v1