我有这样的情况:http://jsfiddle.net/HKHS3/
问题是如何使div
逐行出现,其中一行中的所有div
具有相同的高度,具体取决于最高的实际内容?
因此,根据body
的宽度,行中div
的数量会有所不同,但每次行结束后的div
都应该是明显浮动的开始新的一行。
答案 0 :(得分:8)
每行固定数量
您可以通过创建row
类型div
来包装内部div
元素来实现此目的。
首先,您需要重新构建HTML,如下所示:
<div class="row">
<div>abc</div>
<div>adb djhf kdfhv fkjsh vhf jhds fjhf jh fjhf jh fdjh dh</div>
<div>dhfjgh jfh gkjhfde jghf jgh jfdh gjfhd gjfdhg jfhd gjdhf jhg djhg jdh gjhfd</div>
</div>
(您可以根据需要添加更多这样的行)
然后以下css应该做你需要的:
.row {
display:table-row;
}
.row > div {
width: 100px;
display:inline-block;
vertical-align:top;
border: 1px solid black;
margin: 5px;
height:100%;
}
每行动态数字(不完美)
上述方法的问题在于它要求每行具有固定数量的div
个元素。如果你想要它是动态的并且包装那么你就会遇到一个问题,只用CSS就可以了。你能得到的最接近的是:
div {
width: 100px;
display:inline-block;
vertical-align:top;
margin: 5px;
}
但是元素并不都具有相同的高度,只是你不能说没有边框。因此,添加border
,background-color
或任何其他显示元素高度的样式都会破坏效果。
完全符合要求(需要javascript)
值得一提的是,使用javascript可以实现您想要的效果。我不会包含这样的示例,因为实际的实现将在很大程度上取决于您的真实HTML的设置方式。
实际上,我快速使用了javascript方法,但它使用了JQuery,并且可能也会进行优化:
function updateHeights() {
var maxHeight = 0, lastY = 0, rowDivs = [], allDivs = $("div"), count = allDivs.length;
allDivs.each(function (i) {
var div = $(this), offset = div.offset(), y = offset.top, x = offset.left, h = div.height();
if (h > maxHeight) maxHeight = h;//store the highest value for this row so far
if (lastY == 0) lastY = y;//get the y position if this is the first element
//if new row
if (y > lastY) {
resizeElements(rowDivs, maxHeight);//resize all elements on this row
rowDivs.length = 0;//reset the array of row elements, ready for next row
maxHeight = h;//set maxHeight to first of new row
}
lastY = y;//store current y posible for checking if we have a new row or not
rowDivs.push(div);//add current element to row collection
//check if last item, is so then resize this last row
if(count - 1 == i)
resizeElements(rowDivs, maxHeight);
});
}
function resizeElements(elements, height) {
for (var i = 0; i < elements.length; i++) {
$(elements[i]).height(height);
}
}
$(window).resize(function () {
updateHeights();
});
updateHeights();
答案 1 :(得分:0)
使用jQuery非常简单。对于同一行中的所有div,给出单个类。让我们在我的例子中说'sameheight'。然后使用这个jQuery。
$(document).ready(function(){
var maxHeight = 0;
$(".sameheight").each(function(){
if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});
$(".sameheight").height(maxHeight);
});
对于多行,重复使用不同类的代码。 希望这能解决你的问题。
答案 2 :(得分:0)
试试这个
<script type="text/javascript">
$(document).ready(function () {
var maxHeight = 0;
$('div').each(function () {
var this_div = $(this);
if (maxHeight < this_div.height()) {
maxHeight = this_div.height();
}
})
$('div').css({ 'height': maxHeight.toString() });
})
</script>