24

我正在寻找一种方法来显示始终以页面为中心并漂浮在页面上的确认对话框。

试过了,但它根本不是“始终居中”,因为位置是固定的:

.Popup
{
    text-align:center;
    position: absolute;
    bottom: 10%;
    left: 27%;
    z-index:50;
    width: 400px;
    background-color: #FFF6BD;
    border:2px solid black;
}

任何的想法?谢谢

4

4 回答 4

36

尝试使用这个CSS

#centerpoint {
    top: 50%;
    left: 50%;
    position: absolute;
}

#dialog {
    position: relative;

    width: 600px;
    margin-left: -300px;

    height: 400px;
    margin-top: -200px;
}
<div id="centerpoint">
    <div id="dialog"></div>
</div>

#centerpoint应该是对话框的容器 div

请注意#centerpoint DIV 应该在body元素内或没有位置的元素内:relative; 财产

于 2009-07-30T09:30:44.047 回答
26

CSS3 转换可用于避免硬编码的宽度和边距:

.dialog {
  top: 50%;
  left: 50%;
  -webkit-transform: translateX(-50%) translateY(-50%);
  -moz-transform: translateX(-50%) translateY(-50%);
  -ms-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
}

用法示例: http: //tympanus.net/codrops/2013/06/25/nifty-modal-window-effects/

于 2013-09-22T07:24:23.470 回答
22

与@Toma 的答案相比,您可以在一个元素上做到这一点

#theDiv {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 200px;
    margin-left: -100px;
    height: 50px;
    margin-top: -25px;
    background: yellow;
}
<div id="theDiv" />

这使您可以将其放置在页面上的任何位置,而不管父容器及其position属性如何。

于 2011-11-21T20:30:22.700 回答
-1
.Popup
{
width:400px;
margin-left:auto;
margin-right:auto;
}

那是水平对齐;垂直对齐有点棘手。只需谷歌搜索“css 垂直中心”或其他内容。

于 2009-07-30T09:27:44.537 回答