为什么按钮不居中?

Gov*_*Rai 1 html css

我认为在已知元素上添加一个marginof将使元素居中,因为两边的边距将变得相等。但是,我不确定我哪里出错了:如何将此按钮置于页面中央?autowidth

     p {
           font-family: helvetica, sans-serif;
           font-size: 18px;
       }
       
       button {
           background-color: lightblue;
           color: white;
           padding: 15px 32px;
           border-radius: 4px;
           border: 5px solid lightblue;
           
       }
       
       .upload-button {
           width: 300px;
           margin: 10px auto;
   
       }
       
       button:hover {
           background: white;
           border: 5px solid lightblue;
           color: lightblue;
       }
       
       html, body {
           height: 100%;
       }
       
       body {
           width: 960px;
           margin: auto;
       }
Run Code Online (Sandbox Code Playgroud)
<button id="upload-button" class="upload-button" type="button">why is this button not centered</button>
Run Code Online (Sandbox Code Playgroud)

Dun*_*Luk 5

默认情况下,按钮是内联元素,因此您可以通过div在按钮周围添加一个容器来将其居中,并为该容器提供一个text-align: center属性以正确对齐按钮。

#container {
   text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container">
    <button>Centered button!</button>
</div>
Run Code Online (Sandbox Code Playgroud)

margin: 0 auto当你的元素是块级元素才有效。所以你也可以添加display: block到你的按钮来实现同样的事情。虽然默认情况下这会给按钮一个全角 (100%),所以你也需要给它一个固定的。

#button1 {
  display: block;
  width: 150px;
  margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)
<button id="button1">Centered button!</button>
Run Code Online (Sandbox Code Playgroud)