code 标签仅适用于单行内联代码,如函数名、变量、命令等;多行代码需用 pre + code 组合,否则会塌陷、丢缩进、破坏语义与无障碍支持。

code 标签本身不能实现代码块展示,强行用它包裹多行代码只会塌成一行、丢缩进、破坏语义——这是最常被误踩的坑。
单行代码必须用 code,别套
在段落中提函数名、变量、命令时,code 是唯一语义正确且排版安全的选择。它默认是行内元素,不会撑开上下行距,屏幕阅读器也能准确读作“fetch 函数”而非“f e t c h”。
-
fetch()✅ 正确:等宽字体、基线对齐、无障碍友好 -
fetch()
❌ 错误:自带 margin 和 display: block,塞进 <p> 里会打断段落流</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8272" title="anything-to-html"><img src="https://img.php.cn/upload/skill/000/000/081/179195588450431.jpg" alt="anything-to-html" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill8272" title="anything-to-html" class="overflowclass">anything-to-html</a> <p class="overflowclass">将调研报告、方案对比、数据分析、需求梳理、会议纪要、设计说明、代码评审、学习笔记等任务产物输出为可在浏览器直接打开的单文件 HTML,替代 Markdown 作为最终交付物。Markdown 在信息密度、视觉清晰度和可分享性上已跟不上 AI 产物的丰富度,HTML 能同时承载排版、表格、SVG 等。</p> </div> <a rel="nofollow" href="/xiazai/skill8272" title="anything-to-html" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div>
- 写
x 必须转义为 <code>x ,否则 <li>别给 <code>code加white-space: pre或display: block,它不是为多行设计的
多行代码必须用 组合,缺一不可
只用
,搜索引擎和高亮库认不出这是代码;只用 <pre class="brush:php;toolbar:false;">,所有换行缩进全被浏览器吃掉。二者嵌套才是标准解法:前者保格式,后者定语义。
- 正确结构:
<code>function greet(name) { return `Hello, ${name}!`; }</code> - 错误写法:
function greet() { ... } → 渲染为无缩进单行 - 错误写法:
function greet() { ... }→ 没,Prism.js 不触发高亮,SEO 当普通文本索引
- 所有 HTML 特殊字符必须手动转义:
<div>、<code>"class"、语法高亮依赖外部库,但结构必须先写对
code标签自己不着色、不识别关键字。高亮库(如 highlight.js 或 Prism.js)只认<pre class="brush:php;toolbar:false;"> 这种结构,且 class 值必须准确。
- 支持的 class 写法:
class="js"、<code>class="python"、class="lang-html" - 不识别的写法:
class="javascript"、class="html5"、class="JS"(大小写敏感) - 引入 highlight.js 后必须调用
hljs.highlightAll(),且要在 DOM 加载完成之后执行 - 即使不用高亮,也建议加基础 CSS:
pre设浅灰背景+横向滚动,code设等宽字体+微背景
真正容易被忽略的是转义和 class 命名——漏一个
或写错一个 <code>class="py",高亮就静默失效,而浏览器不会报错,你只能盯着白底黑字干瞪眼。 - 支持的 class 写法:










