2009-12-21 68 views
2

我總是看到這樣的代碼:位置相對DIVS

#container { 
    background:#000000 none repeat scroll 0 0; 
    display:block; 
    overflow:hidden; 
    position:relative; 
    width:100%; 
} 

我認爲相對位置被用於利用左右頂部和底部(PX)的CSS禮儀到div容納相對於它的父元素。像下面的例子那樣單獨使用它有什麼意義?哪些其他屬性受位置相對影響?

回答

3

子元素位置可以受此影響。

將父元素的位置設置爲相對後,當我們嘗試將子元素的位置設置爲絕對時,它將完全相對於父級而不是文檔。

第一個例子

<style> 
    #container 
    { 
     background:red none repeat scroll 0 0; 
     display:block; 
     position:relative; 
     top: 100px; 
     left: 100px; 
     width:100%; 
    } 
    #child 
    { 
     position: absolute; 
     top: 0px; 
     left: 0px; 
    } 

</style> 
<div id="container"> 
    <div id="child"> 
     I am absolutely placed relative to the container and not to the document 
    </div> 
</div> 

第二個例子

<style> 
    #container 
    { 
     background:red none repeat scroll 0 0; 
     display:block; 
     top: 100px; 
     left: 100px; 
     width:100%; 
    } 
    #child 
    { 
     position: absolute; 
     top: 0px; 
     left: 0px; 
    } 

</style> 
<div id="container"> 
    <div id="child"> 
     I am absolutely placed relative to the container and not to the document 
    </div> 
</div> 

嘗試檢查上面的兩個例子,你會看到其中的差別。

+0

舉一個例子,絕對位置的孩子將相對於這個父母而不是窗口 – 2009-12-21 06:56:42

0

我相信這使得它相對於身體元素,因此相對於身體的整個寬度應用「寬度:100%」。