2016-08-20 98 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

相关问题