2013-10-13 39 views
5
div { 
    width: 400px; 
    height: 400px; 
    background: yellow; 
    z-index: 99; 
    margin: 0 auto; 
} 

我有一个div弹出消息,这将是在顶层和页面的中间位置。如何以绝对定位的元素为中心?

但是,如果我设置position:absolute; z-index:99;它将在上面,但margin:0 auto;将无法​​正常工作。

我怎样才能保持它在层的顶部,也显示在中间?

+0

'顶部:50%;'和'右:50%'添加这些特性 –

+0

代替位置:绝对; - 使用位置:相对; – Danield

+0

相对不能覆盖 – Ben

回答

6

通过使用两个嵌套元素(demo)定心与position: absolute;施加作品的元素。

  1. 第一个元素定位绝对放置其上的所有其他元素
  2. 第二个元素只是就像你期望的那样:使用margin: 0 auto;居中它。

HTML:

<div class="outer-div"> 
    <div class="inner-div"> 
     <p>This is a modal window being centered.</p> 
    </div> 
</div> 

CSS:

.outer-div { 
    position: absolute; 
     top: 0; 
     right: 0; 
     bottom: 0; 
     left: 0; 
    z-index: 13; 

    /* 
    * Setting all four values to 0 makes the element as big 
    * as its next relative parent. Usually this is the viewport. 
    */ 
} 

.inner-div { 
    margin: 0 auto; 
    width: 400px; 
    background-color: khaki; 
}