CSS 改变宽度时不居中

CSS not centering when changing width

我有以下代码。它只是使 python 脚本格式化,颜色使用 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>

点击按钮后,代码不会居中。但是,如果您取消注释 CSS 文件中更改宽度的行,它将居中。为什么当我改变宽度时它不居中?

您可以添加 margin: 0 auto; 使 div 像

一样居中
#code{
    display: none;
    text-align: left;
    margin: 0 auto;
    width: 150px;
}

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;
    margin: 0 auto;
    width: 150px;
}
<!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>

text-align 不是居中内容的最佳选择。你最好在容器上使用 flex 布局(例如 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>