I've got a few DIV tags with different amounts of text content.
HTML:
<div id="boxes">
<div id="boxone">
<p>...</p>
</div>
<div id="boxtwo">
<p>...</p>
</div>
<div id="boxthree">
<p>...</p>
</div>
<div id="boxfour">
<p>...</p>
</div>
</div>
They're in a two-by-two layout and their width is fluid:
CSS:
div#boxes {
width: 100%;
}
div#boxes div {
width: 49.9%;
float: left;
}
I want them all the same height.
So, I loop through them and find the height of the tallest one. Then I loop again and set them all to that height.
jQuery:
$(function() {
var maxHeight = 0;
$('div#boxes div').each(function(){
if (maxHeight < $(this).height()) {maxHeight = $(this).height()}
});
$('div#boxes div').each(function(){
$(this).height(maxHeight);
});
});
This works well if the height of the div doesn't need to change again.
But, it fails if I resize the browser window:
If I (a) make the browser wider, then (b) my DIVs get wider, then (c) their text content wraps fewer times, and then (d) my DIVs are too tall.
If I (b) make the browser more narrow, then (b) my DIVs get narrower, then (c) their text content wraps more, and then (d) my DIVs are too short.
How do I both (1) automatically size DIVs to the height of their content like normal, but also (2) keep those multiple DIVs the same height?
For the others who, like me, came here by searching Google for a solution: The fist part of the accepted answer only works when the first div is the highest. I have made some changes to it and now it seems to work in all cases.
var highest = 0;
function sortNumber(a,b) {
return a - b;
}
function maxHeight() {
var heights = new Array();
$('#wrapper2>div').each(function(){
$(this).css('height', 'auto');
heights.push($(this).height());
heights = heights.sort(sortNumber).reverse();
});
highest = heights[0];
$('#wrapper2>div').each(function(){
$(this).css('height', highest);
});
}
$(document).ready(function() {
maxHeight();
})
$(window).resize(maxHeight);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With