: 行内代码元素

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

<code> HTML 元素用于显示其内容,使其样式看起来像一段计算机代码。默认情况下,内容文本会使用 用户代理 的默认等宽字体显示。

试一试

<p>
  The <code>push()</code> method adds one or more elements to the end of an
  array and returns the new length of the array.
</p>
code {
  background-color: #eeeeee;
  border-radius: 3px;
  font-family: "Courier New", monospace;
  padding: 0 3px;
}

属性

此元素仅包含全局属性

示例

包含 <code> 的一段文本

html
<p>
  The function <code>selectAll()</code> highlights all the text in the input
  field so the user can, for example, copy or delete the text.
</p>

结果

注意

要表示多行代码,请将 <code> 元素嵌套在 <pre> 元素中。单独的 <code> 元素仅表示一个代码短语或一行代码。

可以使用 CSS 规则为 code 选择器定义样式,以覆盖浏览器默认的字体。用户设置的偏好可能会覆盖指定的 CSS。

技术摘要

内容类别 流式内容语句内容、明显内容。
允许内容 短语内容.
标签省略 无,起始标签和结束标签都必须存在。
允许父级 任何接受短语内容的元素。
隐式 ARIA 角色 code
允许的 ARIA 角色 任意
DOM 接口 HTMLElement 直到 Gecko 1.9.2(Firefox 4)及之前版本,Firefox 都为此元素实现了 HTMLSpanElement 接口。

规范

规范
HTML
# the-code-element

浏览器兼容性

另见