Search code examples
htmlsemantic-markup

<code> vs <pre> vs <samp> for inline and block code snippets


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.


Solution

  • 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/