Search code examples
htmlpre

Maximum width of <pre>, not wrap text


I am using <pre> tag in my html, it's allocating the whole width of the page, while I need to make it just as long as the text can be. Note that my text is too short, but the <pre> is taking the whole width of the page, so am not looking into wrapping my text to another line as some questions on SO mentioned.


Solution

  • From W3Schools:

    The width attribute of <pre> is not supported in HTML5. Use CSS instead.

    CSS syntax: <div style="width:200px;overflow:auto"><pre>Some
    text</pre></div>
    

    CSS Example: Pre-formatted text with a fixed width

    Source: HTML PRE width Attribute

    Although, as you have pointed out, this is not dynamic. Try these two methods:

    pre {display:table; margin:auto;}
    

    or

    <pre style="border: 1px solid black; margin:auto; display:inline-block;">
        aaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbb
        ccc
    </pre>
    

    Source: Auto width for PRE element, using CSS?