2016-10-03 45 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高興地幫助:)我也添加了一些例子 –