11

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>
markzz
  • 1,185
  • 11
  • 23

2 Answers2

13

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/

Yann Chabot
  • 4,789
  • 3
  • 39
  • 56
  • 2
    Thanks, works well. Just to let you know, the `
    ` tag will print that indentation.  Best to put each line inside the pre tag on the same column as the div tag.
    – markzz Nov 18 '15 at 21:26
0

There's another way if you don't want to create an extra element.

In CSS, Simply set the pre to use display: flex; and assign center to the justify-content property.

<pre style="display: flex; justify-content: center;">int i = 0;
i = i + 80000000000;</pre>