364
votes

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.

9
Use Google Chrome and inspect Rick Strahl's blog: weblog.west-wind.com/posts/2016/May/23/… then use his stylesheet atributes. His code snippets are very clean and easy to copy/read.JoshYates1980
<pre> and its behavior can be kept in mind as the word ”precisely”snr
@snr that's a non sequiturAlkenrinnstet

9 Answers

380
votes

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>
89
votes

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/

43
votes

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.

17
votes

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>
17
votes

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>
10
votes

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>
3
votes

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

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

3
votes

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.

0
votes

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/