2014-03-24 63 views
0

我有一個絕對定位元素的容器div。這些元素都是可變的高度。但是,每行都有一個設置的數字 - 但這些行在標記中沒有以任何方式定義。如何設置高度或允許div擴展到絕對位置元素的高度?

我無法以任何方式修改標記,因爲它是從庫中輸出的(masonry.js)。

我該如何 - 使用CSS或JavaScript(jQuery可用) - 擴展父div的高度以匹配孩子的高度?

我有一個小提琴在這裏顯示問題:http://jsfiddle.net/WZx4N/1/ - 期望的效果是藍色框'拉伸'的紅色框的高度。請記住,盒子的高度是可變的,所以我不能簡單地遍歷行並加上第一列的高度(參見下面的示例圖)。代碼如下小提琴:

CSS

.container{ 
    position:relative; 
    background:blue; 
    min-height:100px; 
} 
.box{ 
    position:absolute; 
    width:75px; 
    height:75px; 
    margin:5px 5px; 
    background:red; 
    border:1px solid black; 
} 

HTML

<div class="container"> 
    <div style="top:0; left:0px;" class="box"></div> 
    <div style="top:0; left:85px;" class="box"></div> 
    <div style="top:0; left:170px;" class="box"></div> 
    <div style="top:0; left:255px;" class="box"></div> 
    <div style="top:0; left:340px;" class="box"></div> 
    <div style="top:85px; left:0px;" class="box"></div> 
    <div style="top:85px; left:85px;" class="box"></div> 
    <div style="top:85px; left:170px;" class="box"></div> 
    <div style="top:85px; left:255px;" class="box"></div> 
    <div style="top:85px; left:340px;" class="box"></div> 
    <div style="top:170px; left:0px;" class="box"></div> 
    <div style="top:170px; left:85px;" class="box"></div> 
    <div style="top:170px; left:170px;" class="box"></div> 
    <div style="top:170px; left:255px;" class="box"></div> 
    <div style="top:170px; left:340px;" class="box"></div> 
</div> 

的每一行循環和鍛鍊的最高元素的高度將無法正常工作作爲元素低於它可能會更短,從而將計算關閉。請看這個例子,看看我的意思是:

block example

請注意:其他答案這個問題找到here不適用由於對我的孩子div的不同高度,而且由於缺乏我需要爲純粹的CSS解決方案。正如我不認爲這是一個重複的問題,我已經搜查了其他類似的問題。

回答

1

您可以遍歷子元素,以確定哪一個是從上最遠的:

var height = 0; 

$('.container > div').each(function() { 
    var $this = $(this), 
     bottom = $this.position().top + $this.outerHeight(); 

    if(bottom > height) { 
     height = bottom; 
    } 
}); 

然後設置高度爲這個孩子的頂部的總和,且該子女的高度。

$('.container').height(height); 
+0

如果每個'.box'上都有空格,你可能需要修改它以將'true'傳遞給'outerHeight'。 http://jsfiddle.net/WZx4N/2/ – ArrayKnight

+0

聰明,現在我明白了。一個試圖使我的複雜化的案例。謝謝 :) – Mike

相關問題