2010-05-06 70 views
1

我有三個的div如下CSS:CSS DIV定位問題

div#container { 
    width: 780px; 
} 
div#photos { 
    width: 780px; 
    height: 300px; 
} 
div#content { 
    position: relative; 
    top: -106px; 
    width: 780px; 
} 


<div id="container"> 
    <div id="photos">photos are here</div> 
    <div id="content">content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer</div> 
</div> 

我的問題是,因爲我已經設置內容層是頂:-106px有很大的差距underneith,當我想「容器」div在「content」div後立即結束。我試圖在「容器」div上設置margin-bottom:-106px,但這並沒有改變「容器」div的高度。

「content」div的高度顯然是不同的,等等。有什麼辦法讓這項工作?

在此先感謝:)

回答

1

我建議不同的方法,是絕對定位你的圖像,然後對容器按內容來與頂邊(或填充如果你需要的背景)。

div#container { 
    width: 780px; 
    margin-top:106px; 
} 
div#photos { 
    width: 780px; 
    height: 300px; 
    position:absolute; 
    top:0; 
    z-index:50; 
} 
div#content { 
    position: relative; 
    width: 780px; 
    z-index:100; 
} 
1

將您的容器div的高度設置爲100%可能會有所幫助。您可以嘗試的另一件事是在您的容器div上設置overflow屬性。溢出:隱藏或溢出:自動都會讓你的容器div有時更好地「包裝」你的其他divs。

請記住,您的瀏覽器里程會有所不同。

1

差距的原因是相對定位不會刪除原來爲該元素創建的空間,即使您將其移動。嘗試將其更改爲「絕對」,然後查看它是否符合您的要求。

1

試着改變你的CSS來

div#container { 
width: 780px; 
position:relative; <--------------- 
} 
div#photos { 
width: 780px; 
height: 300px; 
background: #aaaaaa; 
} 
div#content { 
    position:absolute; <------------ 
    top: 106px;  <------------ 
    width: 780px; 

} 
1

而不是使用position: relative和設置top的,你可以通過設置一個負margin-top實現無空間相同的效果:

div#content { 
    margin-top: -106px; 
    width: 780px; 
}