2013-10-13 98 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; 
}