垂直和水平居中时出现滚动条,无法摆脱它

时间:2013-12-07 23:48:28

标签: html css twitter-bootstrap

使用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中显示的内容似乎“有效”,但出于某种原因它添加了一个垂直滚动条。有趣的是,更改正文的font-sizefont-familyline-height似乎会影响滚动条,因此我认为这与height: 100%和{{{{}}有关。 1}} div。

我喜欢关于如何使这个特定布局正确发生的两个指针,因为我怀疑我这样做很难。

1 个答案:

答案 0 :(得分:1)

为什么不使用内容元素并删除其他内容:

.content {
    background-color: grey;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -150px;
    margin-top: -75px;
    width: 300px;
    height: 150px;
}