csswhitespace

CSS white-space: no wrap, no horizontal scrollbar and maintain white-space when copied


I'm trying to achieve a combination of three goals...

  1. Determine if I should use <code><pre>...</pre></code> or <pre><code>...</code></pre>?

  2. Make code not wrap, not create horizontal scrollbars and not overflow any parent element.

  3. Ensure that when a visitor copies code that the white-space is maintained when they paste it in to any (competent) editor.

So far I've had the most luck with white-space: pre-wrap; however I do not want the text to wrap. If they're interested enough they'll copy-paste it for themselves. While I do not want it to wrap I also do not want it to make the element overflow outside of any parent element and I don't want the text to appear outside of it's direct parent element.

I'd be okay with a horizontal scrollbar for the code itself (pre or code element, whichever) though I'd generally prefer not to.

Just in case it's relevant I don't use any CSS frameworks or the likes, I only do a basic reset...

* {border: 0px; margin: 0px; outline: none; padding: 0px; }

I test in Firefox, then Chrome, then (actual) Opera and then maybe IE if I have sanity to spare. Thoughts please?


Solution

  • I got it working to an accuracy of about 99.8% of the time using the following...

    XHTML

    <pre><code>/* Code here. */</code></pre>
    

    CSS

    pre {white-space: pre; width: 75vmax;}