3

我正在尝试使用以下内容:

<div class="center">
  ...
</div>

CSS:

.center{
    position: absolute;
    height: 50px;
    width: 50px;
    background:red;
    top:calc(50% - 50px/2);
    left:calc(50% - 50px/2);
}

然而,似乎 div 不是位于视口的中心,而是位于包围它的 div 的中心。

如何使用 calc 将 div 定位在屏幕中央?

4

4 回答 4

4

你可以使用新的display: flex

CSS

#overlay {
    height: 100%;
    width: 100%;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}

.dialog {
    margin: auto;
    width: 280px;
}


jsFiddle

浏览器支持

Firefox、Safari 6、IE 11(也许 10)、Opera、Chrome

于 2013-10-28T21:00:27.573 回答
1

你为什么不使用:

.center {
    position: absolute;
    height: 50px;
    width: 50px;
    background: red;
    top: calc(50% - 25px);
    left: calc(50% - 25px);
}

或者:

.center {
    position: absolute;
    height: 50px;
    width: 50px;
    background: red;
    margin-top: -25px;
    margin-left: -25px;
    top: 50%;
    left: 50%;
}
于 2013-10-28T20:11:38.537 回答
1

为什么不使用这个top: 0; bottom: 0; left: 0; right: 0;技巧?

http://jsfiddle.net/3n1gm4/WpYHS/

html:

<div class="centered">
    <h1>Perfectly Centered</h1>
    <h3>This is centered top to bottom and left to right</h3>
</div>

CSS:

.centered {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    width: 50%; /* any width */
    height: 30%; /* any height */
    margin: auto;

    text-align: center;

    background: #deface;
}
于 2013-10-28T21:25:33.047 回答
0

我认为你应该使用:

.center {
    float: none;
    margin-left: auto;
    margin-right: auto;
}
于 2013-10-28T20:57:40.243 回答