htmlformattingpre

Center <pre> Block Without Centering Text


If I wanted to print code on an HTML page, but I want the <pre> block to be centered, but the actual text to be left aligned, how is this done?

Just to make it simple, what would it take to get this to center so that both lines start at the same place.?

<pre>int i = 0;
i = i + 80000000000;</pre>

Solution

  • That is the way you want to do it. Have a container with display: block; around it and text-align: center;. Then, add display: inline-block; to your pre tag and make it text-align: left;

    HTML

    <div class="container">
        <pre>
    int i = 0;
    i = i + 80000000000;
        </pre>
    </div>
    

    CSS

    .container {
       text-align: center;
     }
    
    .container pre {
      display: inline-block;
      text-align: left;
     }
    

    fiddle: https://jsfiddle.net/bvwmnz8z/