2016-08-20 80 views
3

我最近使用display: table作爲我的html以及display: table-cell用於我的body以使我的頁面的所有內容都出現在屏幕的中心。雖然,這與段落,標題,輸入和標籤等(至少我已經測試),它似乎不適用於div元素。
有沒有什麼辦法可以讓div這個元素像其他元素一樣工作?純粹的CSS解決方案將是最好的。當使用顯示器時div不居中:表格單元格

also on Codepen

html { 
 
    display: table; 
 
    height: 100%; 
 
    width: 100%; 
 
    text-align: center; 
 
} 
 
body { 
 
    display: table-cell; 
 
    vertical-align: middle; 
 
} 
 
.hidden { 
 
    display: none; 
 
} 
 
.leaf { 
 
    border-radius: 15px 2px 15px 2px; 
 
    border: 1px solid green; 
 
    background-color: green; 
 
    width: 250px; 
 
    height: 80px; 
 
}
<div class="leaf">Why am I not centered?</div> 
 
<p>And why am I centered?</p>

回答

4

只需添加margin: 0 auto; ..正確地工作。

html { 
 
    display: table; 
 
    height: 100%; 
 
    width: 100%; 
 
    text-align: center; 
 
} 
 
body { 
 
    display: table-cell; 
 
    vertical-align: middle; 
 
} 
 
.hidden { 
 
    display: none; 
 
} 
 
.leaf { 
 
    border-radius: 15px 2px 15px 2px; 
 
    border: 1px solid green; 
 
    background-color: green; 
 
    width: 250px; 
 
    height: 80px; 
 
    margin:0 auto; 
 

 
}
<div class="leaf">Why am I not centered?</div> 
 
<p>And why am I centered?</p>

+0

它,爲什麼它這樣做不過? 'margin:0 auto'規則如何實現這一點? –

+2

當您在已應用了「margin:0 auto」的對象上指定了寬度時,該對象將居中放置在其父容器中。 將'auto'指定爲第二個參數基本上會告訴瀏覽器自動確定左邊距和右邊距,通過將它們設置爲相等來實現。它確保左右邊距將被設置爲相同的大小。第一個參數0表示頂部和底部邊距都將被設置爲0. –

1

只需添加保證金:0汽車;以.leaf類。

html { 
 
    display: table; 
 
    height: 100%; 
 
    width: 100%; 
 
    text-align: center; 
 
} 
 
body { 
 
    display: table-cell; 
 
    vertical-align: middle; 
 
} 
 
.hidden { 
 
    display: none; 
 
} 
 
.leaf { 
 
    margin: 0 auto; 
 
    border-radius: 15px 2px 15px 2px; 
 
    border: 1px solid green; 
 
    background-color: green; 
 
    width: 250px; 
 
    height: 80px; 
 
}
<div class="leaf">Why am I not centered?</div> 
 
<p>And why am I centered?</p>

+1

@Angelos,關於自動技巧的更多信息,請看看[這裏](http://stackoverflow.com/questions/3170772/what -does-AUTO-DO功能於margin0-AUTO) – Divsign

相關問題