<samp>:樣本輸出元素

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

<samp> HTML 元素用於封裝代表電腦程式的樣本(或引用)輸出的內嵌文本。其內容通常使用瀏覽器的預設等寬字體呈現(如 Courier 或 Lucida Console)。

嘗試一下

屬性

此元素僅包括全域屬性

使用注意事項

你可以使用 CSS 規則來覆蓋 <samp> 元素的瀏覽器默認字體;但是,瀏覽器的偏好可能優先於你指定的任何 CSS。

覆蓋默認字體的 CSS 如下所示:

css
samp {
  font-family: "Courier";
}

備註: 如果你需要一個元素來作為你的網站或應用程式 JavaScript 代碼生成的輸出的容器,則應該使用 <output> 元素。

範例

基本範例

在這個簡單的例子中,段落包含了一個程式輸出的例子。

html
<p>
  When the process is complete, the utility will output the text
  <samp>Scan complete. Found <em>N</em> results.</samp> You can then proceed to
  the next step.
</p>

結果

包含使用者輸入的樣本輸出

你可以在 <samp> 區塊中嵌套 <kbd> 元素,以呈現包含使用者輸入文字的例子。例如,考慮以下文本,展示了 Linux(或 macOS)控制台會話的副本:

HTML

html
<pre>
<samp><span class="prompt">mike@interwebz:~$</span> <kbd>md5 -s "Hello world"</kbd>
MD5 ("Hello world") = 3e25960a79dbc69b674cd4ec67a72c62

<span class="prompt">mike@interwebz:~$</span> <span class="cursor"></span></samp></pre>

請注意,使用 <span> 元素允許自定義樣本文本的特定部分的外觀,例如外殼提示符和光標。還要注意,在樣本文本中使用 <kbd> 來表示使用者在提示符處輸入的命令。

CSS

實現我們想要的外觀的 CSS 是:

css
.prompt {
  color: #b00;
}

samp > kbd {
  font-weight: bold;
}

.cursor {
  color: #00b;
}

這使提示符和光標具有相對較細微的顏色,並在樣本文本中加粗鍵盤輸入。

結果

得到的輸出是這樣的:

技術摘要

內容類型 流內容段落型內容、捫及內容。
允許的內容 段落型內容
標籤省略 不允許,開始和結束標籤都是必須的。
允許的父元素 任何接受段落型內容的元素。
隱含的 ARIA 角色 generic
允許的 ARIA 角色 任何
DOM 介面 HTMLElement

規範

Specification
HTML
# the-samp-element

瀏覽器相容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
samp

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

參見