javascripthtmlcsshighlight.js

CSS not centering when changing width


I have the following code. It simply makes the python script formatted, with the colors using highlight.js.

hljs.highlightAll();

 function clicked(){
      if(document.getElementById("code").style.display === "block"){
          document.getElementById("code").style.display = "none" 

      }else{
          document.getElementById("code").style.display = "block" 
      }
  }
html{
    text-align: center;
}

#code{
    display: none;
    text-align: left;
    width: 150px; /* removing this line will center */
}
<!DOCTYPE html>
<html lang="en">
<head>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.7.2/build/styles/atom-one-dark.min.css"
    />
    <script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.7.2/build/highlight.min.js"></script>


</head>
<body>
    <button onclick="clicked()">Show Code</button>
    <pre id="code"><code>print('hello world')</code></pre>
</body>
</html>

After clicking the button, it will not center the code. But if you uncomment the line which changes the width in the CSS file, it centers. Why does it not center when I change the width?


Solution

  • text-align is not the best thing to reach for when centering content. You'd be better off using flex layout on the container (e.g. body).

    hljs.highlightAll();
    
     function clicked(){
          if(document.getElementById("code").style.display === "block"){
              document.getElementById("code").style.display = "none" 
    
          }else{
              document.getElementById("code").style.display = "block" 
          }
      }
    body {
      display: flex;
      align-items: center;
      flex-direction: column;
    }
    
    #code{
        display: none;
        text-align: left;
        width: 150px; /* removing this line will center */
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.7.2/build/styles/atom-one-dark.min.css"
        />
        <script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.7.2/build/highlight.min.js"></script>
    
    
    </head>
    <body>
        <button onclick="clicked()">Show Code</button>
        <pre id="code"><code>print('hello world')</code></pre>
    </body>
    </html>