2016-10-03 87 views
0

我认为在已知的width元素上添加marginauto会使元素居中,因为两边的边距将变得相等。但是,我不确定我要出错的地方:如何将此按钮置于页面上?为什么按钮不居中?

 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; 
 
     }
<button id="upload-button" class="upload-button" type="button">why is this button not centered</button>

+0

你希望它仅水平水平和垂直居中或? –

回答

2

按钮是默认的行内元素,所以你可以通过添加一个容器div按钮周围居中并给予容器text-align: center属性正确对齐按钮。

#container { 
 
    text-align: center; 
 
}
<div id="container"> 
 
    <button>Centered button!</button> 
 
</div>

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

#button1 { 
 
    display: block; 
 
    width: 150px; 
 
    margin: 0 auto; 
 
}
<button id="button1">Centered button!</button>

+0

谢谢,邓肯。你是对的。但是,如果没有div和文本对齐中心,它怎么没有居中。我只问,因为身体有一个960像素的定义和按钮是300像素,所以不应该在按钮中心的自动边距吗? –

+0

太棒了!我不知道保证金自动仅适用于块级元素..我会在6分钟内接受答案,当我让我:) –

+1

@GovindRai高兴地帮助:)我也添加了一些例子 –