使用 Bootstrap 3.0.3,我试图将具有硬编码宽度和高度的 div 水平和垂直居中。 JSFiddle 中包含最新代码,此处也报告与 SO 关于 JSFiddle 的规则一致。
http://jsfiddle.net/alex_kurilin/pNYg9/
HTML:
<div class="text-center full-height">
<div class="inline full-height">
<div class="fake-table full-height">
<div class="fake-table-cell full-height">
<div class="content fake-table">
<div class="fake-table-cell">foobar</div>
</div>
</div>
</div>
</div>
</div>
CSS:
html, body {
height: 100%;
}
.fake-table {
display: table;
}
.fake-table-cell {
display: table-cell;
vertical-align: middle;
}
.inline {
display: inline-block;
}
.text-center {
text-align: center;
}
.full-height {
height: 100%;
}
.content {
background-color: grey;
width: 300px;
height: 150px;
}
我在 JSFiddle 中展示的内容似乎“有效”,但出于某种原因它添加了一个垂直滚动条。有趣的是,改变 body 的 font-size
、font-family
和 line-height
似乎会影响滚动条,因此我想与 height: 100%
和 inline-block
div 有关。
我希望得到关于如何使这个特定布局正确发生的两个指示,因为我怀疑我这样做很困难。
最佳答案
为什么不只使用内容元素并删除其他元素:
.content {
background-color: grey;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -75px;
width: 300px;
height: 150px;
}
关于html - 垂直和水平居中时出现滚动条,无法摆脱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20448162/