Search code examples
htmlcsspre

Render spans inside pre tag (in the HTML, not displayed as text to the user)


Is it possible to render spans within a pre tag?

Basically I am showing code snippets on my site, you can see them here. I want to wrap some parts of the code in "span" tags.

Right now when I add <span> inside of the text to go inside the <pre>, it just renders as text, for example My code is so <span>cool</span> and I love it. How can I get the proper word-breaks and line-spacing of pre, while still rendering span tags?


Solution

  • The <pre> tag will render its contents literally. You can make whitespace within another tag significant but render tags within as HTML using some CSS. For example:

    .code {
        white-space: pre;
    
        /* If you want to use a monospace font like <pre> does by default */
        font-family: monospace;
    }
    
    span {
        font-weight: bold;
    }
    <div class="code">
        My code is so <span>cool</span> and I love it
    </div>