如何设计一个CSS以实现居中浮动确认对话框?

30

我在寻找一种方法来显示一个确认对话框,它始终居中于页面并浮动在页面之上。

尝试过那种方式,但它并不真正“始终居中”,因为位置是固定的:

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

有什么想法吗? 谢谢

4个回答

37

试试使用这个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 元素内或在不具有position: relative; 属性的元素内部。


我试过了,在IE、Firefox、Chrome、Safari和Opera中都可以运行。 - Cristian Toma

33

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/


2
你需要使用 position: fixed; 才能使其正常工作,当我尝试使用 position: absolute 时,它只显示在左边一半。 - hultqvist

23

相较于@Toma的答案,您可以在一个元素上完成它

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

这允许您将其放置在页面上的任何位置,而不受父容器及其position属性的影响。


-1
.Popup
{
width:400px;
margin-left:auto;
margin-right:auto;
}

这是水平对齐; 垂直对齐有一点棘手。只需在Google中搜索“CSS垂直居中”或类似内容。


这只是将对话框置于其父容器的中心位置,但它并没有浮动在页面上方。 - Cristian Toma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接