我最近一直在使用
是否有任何方法可以使这对
display: table
以及display: table-cell
来让我的html
页面中的所有内容都居中显示。虽然对于段落、标题、输入框和标签等元素这样做是有效的(至少我测试过是有效的),但是似乎对于div
元素无效。
是否有任何方法可以使这对
div
元素像其他元素一样有效?最好采用纯CSS解决方案。
示例(也可在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>
margin: 0 auto
规则是如何让它做到的? - Angelos Chalarismargin: 0 auto
的对象上指定宽度时,该对象将居中于其父容器内。将第二个参数指定为auto
基本上告诉浏览器自动确定左右边距,它通过设置相等的边距来实现。它保证左右边距将被设置为相同的大小。第一个参数0表示顶部和底部边距都将被设置为0。 - Prasath V