412

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Steve Bennett
  • 114,604
  • 39
  • 168
  • 219

9 Answers9

434

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>
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
  • 11
    This might be the correct way to go, but I still think it's stupid. The HTML-devs foresaw the need for a `` tag, but decided we'd only ever write one-line? Or I guess, because they didn't want to have two tags, one block and one inline? Still... what's wrong with making `` block-level with CSS? I thought we were supposed to write "semantic" HTML. `` is good and semantic, but `
    ` not so much.
    – mpen Jan 06 '11 at 08:43
  • 12
    I disagree. The opposite of preformatted text is just plain old text in your document. Making `` block-level with CSS is unsemantic. This way is [recommended in HTML5](http://www.w3.org/TR/html5/grouping-content.html#the-pre-element). – Josh Lee Jan 06 '11 at 14:11
  • 2
    Problem with `
    ` is it modifies whitespace processing as well: all spaces are preserved, and wrapping is switched off. Unless there's a way to switch this off?
    – Steve Bennett Jan 08 '11 at 23:55
  • 4
    @Steve Bennett, in CSS `white-space: normal;` Though I fail to see why you would do this for code. Also this `
    ` thing is stupid, the `
    ` tag is defined very clearly in the standards as "computer code" (and other things) as mentioned by @jleedev.   Is it because you think `` is a better name? sorry that doesn't make it more semantic. There's a similar case with the tag `
    `, it doesn't really sound like "author", but the standard says that's what it's for, so it-is.
    – srcspider Feb 23 '11 at 02:15
  • see also http://dev.w3.org/html5/spec-author-view/the-code-element.html#the-code-element – Maslow Sep 20 '11 at 00:14
  • "Though I fail to see why you would do this for code." - because whitespace is not significant in all languages, notably XML. "Is it because you think is a better name?" - as I said, the issue is the lack of line wrapping with
    .
    – Steve Bennett Nov 28 '11 at 13:00
  • 8
    -1. The OP's central question was about how to accomplish block snippets that wrap. You've addressed inline code, as well as block code that must *not* wrap, but this doesn't address the OP's primary question. – Asad Saeeduddin May 31 '13 at 00:51
  • `` has a larger line space than `
    ` and CSS has `white-space: pre;` which simulates `
    ` replacing `
    `
    – noobninja Jul 30 '16 at 14:42
100

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>&lt;code&gt;</code> tag.

<pre>
Here's a very long pre-formatted formatted using the &lt;pre&gt; 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/

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
46

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.

slebetman
  • 109,858
  • 19
  • 140
  • 171
  • yeah, I'm starting to think so, too. I did ask for a solution without classes, but it looks like there isn't a good one. – Steve Bennett Jan 08 '11 at 23:57
  • 6
    @Steve: The main thing is to define a default `` block without a class for the most common use case. Then anyone wanting to do the uncommon thing only needs to add the class. Doing it any other way will still be asking the user to type extra. This way the user can think of it as adding a special tag rather than using a completely different structure. – slebetman Jan 09 '11 at 00:19
  • I did this but also had to include `white-space: pre;` style in my `.codeblock` class – Jake Tyler Mar 05 '23 at 20:05
19

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>
Community
  • 1
  • 1
vsync
  • 118,978
  • 58
  • 307
  • 400
  • I'm surely missing something, but apparently, this is the only I found way to show raw HTML code (for debugging purpose) in WordPress/PHP templates... – sphakka Apr 02 '17 at 09:37
  • @sphakka (& vsync), See my answer here suggesting the use of ` – www-0av-Com Mar 19 '18 at 20:20
  • 1
    @user1863152 - it's a very bad use of a textarea IMHO since the code cannot be highlighted by external script, like [Prism](http://prismjs.com/) for example. and also, it doesn't fits the height and width of the content, like `` does, or any other `block` element does.. i wouldn't recommend it as a real solution, only as a theoretical one. – vsync Mar 20 '18 at 10:34
  • @vsync, yes it's horses for courses (& I gave you an upvote btw). I use textarea for my needs. I tried xmp and can't recall why I found xmp unsatisfactory for my needs. Of course its deprecated status certainly discourages. I use PRE when I need to highlight and CODE for inline use. I can't imagine how Prism highlights within an XMP -- some CSS wizardry? – www-0av-Com Mar 21 '18 at 14:32
  • I'm not too sure about this. Yes, it works, but deprecated since 3.2 and removed completely in 5? While not many tags have been completely removed from browsers - `` is one example - I would be anxious about using this for anything that needs to be future-proof. – spacer GIF Jun 19 '19 at 11:39
17

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 &lt;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>
Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
ekim
  • 219
  • 2
  • 3
11

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 &amp; still acts as an escape char..
      Eg: &lt;u&gt;(text)&lt;/u&gt;
</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 &amp; still acts as an escape char..
      Eg: &lt;u&gt;(text)&lt;/u&gt;</textarea>

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

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

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

<code>CODE: Example text with Newlines,
tabs & space,
  html tags etc <b>are interpreted, not displayed</b>.
    However, note that &amp; still acts as an escape char..
      Eg: &lt;u&gt;(text)&lt;/u&gt;
</code>
www-0av-Com
  • 707
  • 10
  • 14
6

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.

Stokely
  • 12,444
  • 2
  • 35
  • 23
3

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

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

Michael Cole
  • 15,473
  • 7
  • 79
  • 96
0

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/

proseosoc
  • 1,168
  • 14
  • 23