问题:
是否可以使用边距将 DIV 垂直居中:自动自动;?为什么不垂直对齐:中间;工作吗?
答案:
关于 Margin:
不幸的是,margin:auto auto;没有实现垂直居中。页边距不适用于块级元素,例如用于垂直对齐的 DIV。因此,margin:top:auto 和 margin-bottom:auto 是无效的。
关于vertical-align:middle;:
vertical-align:middle;仅适用于内联元素,不适用于 DIV 等块级元素。
解决方法:
由于无法使用边距垂直居中 DIV,因此有一个解决方法推荐。一种行之有效的方法是在类似表格的容器中使用嵌套元素:
.container { display: table; height: 100%; position: absolute; overflow: hidden; width: 100%; } .helper { position: absolute; top: 50%; display: table-cell; vertical-align: middle; } .content { position: relative; top: -50%; margin: 0 auto; width: 200px; border: 1px solid orange; }
<div class="container"> <div class="helper"> <div class="content"> <p>stuff</p> </div> </div> </div>
以上是我可以使用'margin: auto”将 DIV 垂直居中吗?的详细内容。更多信息请关注PHP中文网其他相关文章!