2010-04-13 74 views
0

我有以下的HTML + CSS的標記:一個div其孩子的位置設置高度:絕對

<div id="protofade" style="position: relative;"> 
    <div style="position: absolute;"><img src="slide-01.jpg"></div> 
    <div style="position: absolute;"><img src="slide-02.jpg"></div> 
    <div style="position: absolute;"><img src="slide-03.jpg"></div> 
</div> 

注意,幻燈片是絕對定位相對定位的元素內部,使得左上邊角的所有幻燈片都排列在一起。所有幻燈片的高度相同,但高度不是預先確定的,因此這個問題:「protofade」div沒有高度。是否有任何CSS技巧可以使此div與第一張幻燈片一樣高,而無需明確指定height: NNpx

回答

1
<div id="protofade" style="position: relative;"> 
<div style="position: absolute;"><div style="width: 200px; height: 50px; background: #F66;"></div></div> 
<div style="position: absolute;"><div style="width: 200px; height: 50px; background: #6F6;"></div></div> 
<div style="position: absolute;"><div style="width: 200px; height: 50px; background: #66F;"></div></div> 
<div style="visibility:hidden;"><div style="width: 200px; height: 50px; background: red;"> This should be a second copy of slide one </div></div> 
</div> 

上面的代碼顯示您的原代碼(除與div的,因爲每斯科特·布朗,上文),通過加入「幻燈片1」的第二拷貝,定位爲與默認的算法,但具有其框隱藏。相應地,它的容器,protofade必須足夠大以容納箱子,即使箱子沒有顯示。

+0

這就是我最終這樣做的......但那是幾個月前:) – 2011-02-22 07:49:33

1

有一個jQuery的答案。我不相信這可以通過CSS來完成,因爲您需要能夠獲得第一個div的高度。

我出在這裏:http://jsfiddle.net/thewebdes/FHgz5/

僅供參考,這裏有一個運行代碼的下降:

HTML

<!-- 
using DIVs in place of IMGs 
setting height to these DIVs, all equal as specified 
--> 
<div id="protofade" style="position: relative;"> 
    <div style="position: absolute;"><div style="width: 200px; height: 50px; background: #F66;"></div></div> 
    <div style="position: absolute;"><div style="width: 200px; height: 50px; background: #6F6;"></div></div> 
    <div style="position: absolute;"><div style="width: 200px; height: 50px; background: #66F;"></div></div> 
</div> 

CSS

/* border set to show height given to DIV */ 
#protofade { border: 5px solid #000; } 

JS

// CSS height set based on the height of the first DIV 
// First DIV chosen as all heights will be the same anyway so it shouldn't matter. 
$('#protofade').css("height", $('#protofade div:eq(1)').height()); 
+0

我爲此使用原型庫。您的解決方案有效,但有一個主要問題:根據瀏覽器類型以及瀏覽器緩存是否已啓動,'#protofade div:eq(1)'的高度可能正確也可能不正確。當緩存未啓動時,它可能是0px的document.ready事件,或者在Internet Explorer上等於32px(等於IE在圖片未加載時使用的佔位符圖片的高度)。 – 2011-02-22 07:58:03

相關問題