<代码>与 <预>与 用于内联和块代码片段

发布于 2024-10-10 17:51:30 字数 468 浏览 3 评论 0 原文

我的网站将有一些内联代码(“当使用 foo() 函数时...”)和一些块片段。这些往往是 XML,并且有很长的行,我更喜欢浏览器将其换行(即,我不想使用

)。我还想在块片段上设置 CSS 格式。

看来我不能同时使用 ,因为如果我在上面放置 CSS 块属性(使用 display: block;),它会破坏内联片段。

我很好奇人们在做什么。使用 表示块,使用 表示内联?使用

或类似的东西?

我想让实际的 HTML 尽可能简单,避免类,因为其他用户将维护它。

My site is going to have some inline code ("when using the foo() function...") and some block snippets. These tend to be XML, and have very long lines which I prefer the browser to wrap (i.e., I don't want to use <pre>). I'd also like to put CSS formatting on the block snippets.

It seems that I can't use <code> for both, because if I put CSS block attributes on it (with display: block;), it will break the inline snippets.

I'm curious what people do. Use <code> for blocks, and <samp> for inline? Use <code><blockquote> or something similar?

I'd like to keep the actual HTML as simple as possible, avoiding classes, as other users will be maintaining it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

壹場煙雨 2024-10-17 17:51:30

使用 表示可以换行的内联代码,使用

 表示不能换行的块代码。  用于示例输出,因此我会避免使用它来表示示例代码(读者要输入)。这就是 Stack Overflow 所做的事情。

(更好的是,如果你想易于维护,让用户以 Markdown 方式编辑文章,那么他们就不必记住使用

。)

HTML5 同意这在 pre 元素中”

pre 元素表示预格式化文本块,其中结构由印刷约定而不是元素表示。

可以使用 pre 元素的一些示例:

  • 包括计算机代码片段,其结构根据该语言的约定表示。

[…]

为了表示计算机代码块,pre 元素可以与 code 元素一起使用;为了表示计算机输出块,pre 元素可以与 samp 元素一起使用。同样,kbd 元素可以在 pre 元素中使用来指示用户要输入的文本。

在下面的代码片段中,提供了一个计算机代码示例。

<p>This is the <code>Panel</code> constructor:</p>
<pre><code>function Panel(element, canClose, closeHandler) {
      this.element = element;
      this.canClose = canClose;
      this.closeHandler = function () { if (closeHandler) closeHandler() };
    }</code></pre>

Use <code> for inline code that can wrap and <pre><code> for block code that must not wrap. <samp> is for sample output, so I would avoid using it to represent sample code (which the reader is to input). This is what Stack Overflow does.

(Better yet, if you want easy to maintain, let the users edit the articles as Markdown, then they don’t have to remember to use <pre><code>.)

HTML5 agrees with this in “the pre element”:

The pre element represents a block of preformatted text, in which structure is represented by typographic conventions rather than by elements.

Some examples of cases where the pre element could be used:

  • Including fragments of computer code, with structure indicated according to the conventions of that language.

[…]

To represent a block of computer code, the pre element can be used with a code element; to represent a block of computer output the pre element can be used with a samp element. Similarly, the kbd element can be used within a pre element to indicate text that the user is to enter.

In the following snippet, a sample of computer code is presented.

<p>This is the <code>Panel</code> constructor:</p>
<pre><code>function Panel(element, canClose, closeHandler) {
      this.element = element;
      this.canClose = canClose;
      this.closeHandler = function () { if (closeHandler) closeHandler() };
    }</code></pre>

笛声青案梦长安 2024-10-17 17:51:30

我完全错过了一些事情:

 的非换行行为可以用 CSS 控制。所以这给出了我正在寻找的确切结果:

code { 
    background: hsl(220, 80%, 90%); 
}

pre {
    white-space: pre-wrap;
    background: hsl(30,80%,90%);
}
Here's an example demonstrating the <code><code></code> tag.

<pre>
Here's a very long pre-formatted formatted using the <pre> tag. Notice how it wraps?  It goes on and on and on and on and on and on and on and on and on and on...
</pre>

http://jsfiddle.net/9mCN7/

Something I completely missed: the non-wrapping behaviour of <pre> can be controlled with CSS. So this gives the exact result I was looking for:

code { 
    background: hsl(220, 80%, 90%); 
}

pre {
    white-space: pre-wrap;
    background: hsl(30,80%,90%);
}
Here's an example demonstrating the <code><code></code> tag.

<pre>
Here's a very long pre-formatted formatted using the <pre> tag. Notice how it wraps?  It goes on and on and on and on and on and on and on and on and on and on...
</pre>

http://jsfiddle.net/9mCN7/

你与清晨阳光 2024-10-17 17:51:30

就我个人而言,我会使用 因为这是语义上最正确的。然后,为了区分内联代码和块代码,我将添加一个类:

<code class="inlinecode"></code>

用于内联代码或:

<code class="codeblock"></code>

用于代码块。取决于哪个不太常见。

Personally I'd use <code> because that's the most semantically correct. Then to differentiate between inline and block code I'd add a class either:

<code class="inlinecode"></code>

for inline code or:

<code class="codeblock"></code>

for code block. Depending on which is less common.

指尖凝香 2024-10-17 17:51:30

使用(过时的)</code></a> 标签:

;
<div>
  <输入占位符='写一些东西'值='测试'>
</div>

非常遗憾这个标签已被弃用,但是它仍然可以在浏览器上使用,它是一个糟糕的标签。无需逃避其中的任何东西。多么高兴啊!


使用

<textarea readonly rows="4" style="background:none; border:none; resize:none; outline:none; width:100%;">
<div>
  <input placeholder='write something' value='test'>
</div>
</textarea>

Show HTML code, as-is, using the (obsolete) <xmp> tag:

<xmp>
<div>
  <input placeholder='write something' value='test'>
</div>
</xmp>

It is very sad this tag has been deprecated, but it does still works on browsers, it it is a bad-ass tag. no need to escape anything inside it. What a joy!


Show HTML code, as-is, using the <textarea> tag:

<textarea readonly rows="4" style="background:none; border:none; resize:none; outline:none; width:100%;">
<div>
  <input placeholder='write something' value='test'>
</div>
</textarea>

别念他 2024-10-17 17:51:30

对于正常内联 使用:

<code>...</code>

对于需要阻塞 的每个地方,使用

<code style="display:block; white-space:pre-wrap">...</code>

或者,定义一个 断裂衬里块标签 (没有课程)

<script>
</script>
<style>
  codenza, code {}     /*  noop mnemonic aide that codenza mimes code tag  */
  codenza {display:block;white-space:pre-wrap}
</style>`

测试:
(注意:以下是使用 data: URI 协议/方案的 scURIple,因此 %0A nl 格式代码对于保留此类数据至关重要当剪切并粘贴到 URL 栏中进行测试时 - 所以 view-source: (ctrl-U) 看起来不错 every< /em> 下面一行带有 %0A

data:text/html;charset=utf-8,<html >
<script>document.write(window.navigator.userAgent)</script>
<script></script>
<style>
  codenza, code {}     /*  noop mnemonic aide that codenza mimes code tag  */
  codenza {display:block;white-space:pre-wrap}
</style>
<p>First using the usual <code> tag
<code>
  %0A     function x(arghhh){ 
  %0A          return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
  %0A     }
</code>
and then 
<p>with the tag blocked using pre-wrapped lines
<code style=display:block;white-space:pre-wrap> 
  %0A     function x(arghhh){ 
  %0A          return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
  %0A     }
</code>
<br>using an ersatz tag
<codenza>
  %0A     function x(arghhh){ 
  %0A          return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
 %0A     }
</codenza>
</html>

For normal inlined <code> use:

<code>...</code>

and for each and every place where blocked <code> is needed use

<code style="display:block; white-space:pre-wrap">...</code>

Alternatively, define a <codenza> tag for break lining block <code> (no classes)

<script>
</script>
<style>
  codenza, code {}     /*  noop mnemonic aide that codenza mimes code tag  */
  codenza {display:block;white-space:pre-wrap}
</style>`

Testing:
(NB: the following is a scURIple utilizing a data: URI protocol/scheme, therefore the %0A nl format codes are essential in preserving such when cut and pasted into the URL bar for testing - so view-source: (ctrl-U) looks good preceed every line below with %0A)

data:text/html;charset=utf-8,<html >
<script>document.write(window.navigator.userAgent)</script>
<script></script>
<style>
  codenza, code {}     /*  noop mnemonic aide that codenza mimes code tag  */
  codenza {display:block;white-space:pre-wrap}
</style>
<p>First using the usual <code> tag
<code>
  %0A     function x(arghhh){ 
  %0A          return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
  %0A     }
</code>
and then 
<p>with the tag blocked using pre-wrapped lines
<code style=display:block;white-space:pre-wrap> 
  %0A     function x(arghhh){ 
  %0A          return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
  %0A     }
</code>
<br>using an ersatz tag
<codenza>
  %0A     function x(arghhh){ 
  %0A          return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
 %0A     }
</codenza>
</html>
寄风 2024-10-17 17:51:30

考虑 TextArea

人们通过 Google 找到此内容并寻找更好的方法来管理其摘要的显示,还应该考虑 可能出现的地方)。

例如,要显示受控换行的单行,请考虑

<textarea rows=5 cols=100 readonly>Example text with Newlines,
tabs & space,
  html tags etc <b>displayed</b>.
    However, note that & still acts as an escape char..
      Eg: <u>(text)</u>
</textarea>

为了比较所有...

<h2>Compared: TEXTAREA, XMP, PRE, SAMP, CODE</h2>
<p>Note that CSS can be used to override default fixed space fonts in each or all these.</p>
    
    
<textarea rows=5 cols=100 readonly>TEXTAREA: Example text with Newlines,
tabs & space,
  html tags etc <b>displayed natively</b>.
    However, note that & still acts as an escape char..
      Eg: <u>(text)</u></textarea>

<xmp>XMP: Example text with Newlines,
tabs & space,
  html tags etc <b>displayed natively</b>.
    However, note that & (&) will not act as an escape char..
      Eg: <u>(text)</u>
</xmp>

<pre>PRE: Example text with Newlines,
tabs & space,
  html tags etc <b>are interpreted, not displayed</b>.
    However, note that & still acts as an escape char..
      Eg: <u>(text)</u>
</pre>

<samp>SAMP: Example text with Newlines,
tabs & space,
  html tags etc <b>are interpreted, not displayed</b>.
    However, note that & still acts as an escape char..
      Eg: <u>(text)</u>
</samp>

<code>CODE: Example text with Newlines,
tabs & space,
  html tags etc <b>are interpreted, not displayed</b>.
    However, note that & still acts as an escape char..
      Eg: <u>(text)</u>
</code>

Consider TextArea

People finding this via Google and looking for a better way to manage the display of their snippets should also consider <textarea> which gives a lot of control over width/height, scrolling etc. Noting that @vsync mentioned the deprecated tag <xmp>, I find <textarea readonly> is an excellent substitute for displaying HTML without the need to escape anything inside it (except where </textarea> might appear within).

For example, to display a single line with controlled line wrapping, consider <textarea rows=1 cols=100 readonly> your html or etc with any characters including tabs and CrLf's </textarea>.

<textarea rows=5 cols=100 readonly>Example text with Newlines,
tabs & space,
  html tags etc <b>displayed</b>.
    However, note that & still acts as an escape char..
      Eg: <u>(text)</u>
</textarea>

To compare all...

<h2>Compared: TEXTAREA, XMP, PRE, SAMP, CODE</h2>
<p>Note that CSS can be used to override default fixed space fonts in each or all these.</p>
    
    
<textarea rows=5 cols=100 readonly>TEXTAREA: Example text with Newlines,
tabs & space,
  html tags etc <b>displayed natively</b>.
    However, note that & still acts as an escape char..
      Eg: <u>(text)</u></textarea>

<xmp>XMP: Example text with Newlines,
tabs & space,
  html tags etc <b>displayed natively</b>.
    However, note that & (&) will not act as an escape char..
      Eg: <u>(text)</u>
</xmp>

<pre>PRE: Example text with Newlines,
tabs & space,
  html tags etc <b>are interpreted, not displayed</b>.
    However, note that & still acts as an escape char..
      Eg: <u>(text)</u>
</pre>

<samp>SAMP: Example text with Newlines,
tabs & space,
  html tags etc <b>are interpreted, not displayed</b>.
    However, note that & still acts as an escape char..
      Eg: <u>(text)</u>
</samp>

<code>CODE: Example text with Newlines,
tabs & space,
  html tags etc <b>are interpreted, not displayed</b>.
    However, note that & still acts as an escape char..
      Eg: <u>(text)</u>
</code>

晚雾 2024-10-17 17:51:30

这是一个普通、非 JavaScript 的 HTML 解决方案,使用起来非常简单,并且优于使用

 元素,或者严厉的 JavaScript 解决方案,这些解决方案总是矫枉过正。这个技巧我已经用了20年了!它适用于所有新旧浏览器。今天的孩子们未能学习旧的方法。

它允许您的用户快速剪切和粘贴代码示例。它还允许您快速、轻松地将代码放入 HTML 元素中,而无需转义通常必须执行的所有 <> 字符使用

使用

<textarea class="code" contenteditable="true" spellcheck="false" aria-label='Code Sample'>
  My Sample Bookmark:
  <a href="#bookmark1" id="b1" title="View my bookmark" target="_blank" rel="noreferrer nofollow noopener" accesskey="a" tabindex="0" aria-label="Bookmark">Got to My Bookmark</a>
</textarea>

...使用一些简单的 CSS 样式...

<style>
        textarea.code {
            display: block;
            width: 90%;
            min-height: 5em;
            overflow-y: auto;
            overflow-x: hidden;
            font-family: monospace;
            border: 1px solid #bbb;
            padding: 1em;
            white-space:pre-wrap;
        }
</style>

请注意,它看起来像常规等宽 < ;code> 但是块级的,支持

 等文本格式,长文本现在换行,代码框大小可控,并允许更灵活地显示大型 HTML 或用户可以更轻松地访问脚本块。

顺便说一句......您仍然可以使用

。对于较小的例子我仍然这样做。并且不用担心使用 

Here is a PLAIN, non-JavaScripted, HTML solution that is very simple to use, and superior to using <pre> and <code> elements, or heavy-handed JavaScript solutions which are always overkill. I have been using this trick for 20 years! It works in all browsers, old and new. Kids today have just failed to learn the old ways.

It allows your users to cut-and-paste code samples quickly. It also allows you to drop you code into an HTML element quickly, hassle-free, without having to escape all the < and > characters you normally have to do when using <code>.

Use the <textarea> element to share code, like so:

<textarea class="code" contenteditable="true" spellcheck="false" aria-label='Code Sample'>
  My Sample Bookmark:
  <a href="#bookmark1" id="b1" title="View my bookmark" target="_blank" rel="noreferrer nofollow noopener" accesskey="a" tabindex="0" aria-label="Bookmark">Got to My Bookmark</a>
</textarea>

...with some simple CSS styling...

<style>
        textarea.code {
            display: block;
            width: 90%;
            min-height: 5em;
            overflow-y: auto;
            overflow-x: hidden;
            font-family: monospace;
            border: 1px solid #bbb;
            padding: 1em;
            white-space:pre-wrap;
        }
</style>

Notice that it looks like regular monospace <code> but is block-level, honors text formats like <pre>, long text now wraps, the code box size is controllable, and allows more flexible displays of large HTML or script blocks users can more easily access.

BTW....you can still use <pre><code>. I still do for smaller examples. And don't worry about semantic or accessibility issues using <textarea> as it is a replaced element and has a more versatile use. If you are worried, then simply add an ARIA label to your <textarea>, like I have done above.

南薇 2024-10-17 17:51:30

考虑 Prism.js: https://prismjs.com/#examples

它使得

 ; 有效且有吸引力。

Consider Prism.js: https://prismjs.com/#examples

It makes <pre><code> work and is attractive.

半世晨晓 2024-10-17 17:51:30

这适用于我在前端显示代码:

<style>
.content{
    height:50vh;
    width: 100%;
    background: transparent;
    border: none;
    border-radius: 0;
    resize: none;
    outline: none;
}
.content:focus{
    border: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
}
</style>

<textarea class="content">
<div>my div</div><p>my paragraph</p>
</textarea>

查看实时演示: https://jsfiddle.net/bytxj50e/

This works for me to display code in frontend:

<style>
.content{
    height:50vh;
    width: 100%;
    background: transparent;
    border: none;
    border-radius: 0;
    resize: none;
    outline: none;
}
.content:focus{
    border: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
}
</style>

<textarea class="content">
<div>my div</div><p>my paragraph</p>
</textarea>

View Live Demo: https://jsfiddle.net/bytxj50e/

你げ笑在眉眼 2024-10-17 17:51:30

看来我不能同时使用 ,因为如果我把 CSS
其上的块属性(使用 display: block;),它将破坏
内联片段。


一个简单的解决方案是将 display: block; 声明放在 div > 中。代码{}规则。这样,block 显示样式将仅适用于作为

的直接后代的 标记,以及任何出现在

或其他文本范围标记内的实例将保留默认的 inline 显示样式。如果网站使用更多语义标记(应该),则可以扩展此规则以包括

div > code, article > code, section > code, aside > code {
display: block;
}

说到语义,如果我们要把 W3C 的话当作福音,他们确实在 HTML5 规范

代码元素表示计算机代码的片段。这可能是
XML 元素名称、文件名、计算机程序或任何其他
计算机可以识别的字符串。

(我的重点)

按照你的意愿去做(也许他们的意思是“一个计算机程序名称”),但我不认为将 重新设计为块级元素可能被认为是一种可怕的罪恶。

It seems that I can't use <code> for both, because if I put CSS
block attributes on it (with display: block;), it will break the
inline snippets.

One simple solution to that would be to put the display: block; declaration inside a div > code {} rule. That way the block display style would only apply to <code> tags that are the immediate descendants of a <div>, and any instances appearing inside a <p>, <h2> or other text span tag would retain the default inline display style. If the site uses more semantic mark-up (it should) this rule could be extended to include <article>, <section> and <aside>:

div > code, article > code, section > code, aside > code {
display: block;
}

And speaking of semantics, if we are to take the W3C's word as gospel, they do say in the HTML5 specification that

The code element represents a fragment of computer code. This could be
an XML element name, a filename, a computer program, or any other
string that a computer would recognize.

(my emphasis)

Make of that what you will (perhaps they meant to say "a computer program name"), but I don't think restyling <code> as a block-level element could be considered a terrible sin.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文