Skip to content

Instantly share code, notes, and snippets.

@dieseltravis
Created November 4, 2008 15:24
Show Gist options
  • Save dieseltravis/22148 to your computer and use it in GitHub Desktop.
Save dieseltravis/22148 to your computer and use it in GitHub Desktop.
use jQuery to set elements to have equal heights, factoring in min-heights and vertical padding
// call this to reset the size to the columns
function setColumnsEqualHeight()
{
// some example items to measure and resize
var $toMeasure = $("#content-left-shadow, #content-middle, #content-right-shadow, #secondary-nav");
var $toResize = $("#content-bottom-container, #content-left-shadow, #content-middle, #content-right-shadow");
setEqualHeight($toMeasure, $toResize);
}
// call the helper method for both ready and load to make sure stuff is sized as dynamically as possible
$(document).ready(function() {
setColumnsEqualHeight();
});
$(window).load(function() {
// make sure the height hasn't been affected by any other slow loading content (images, JS, etc)
setColumnsEqualHeight();
});
// equal height code
function setEqualHeight($toMeasure, $toResize) {
if ($toMeasure.length > 0 && $toResize.length > 0) {
// set back to auto for dynamic content
$toResize.css("height", "auto");
var heights = [];
for (var i = 0; i < $toMeasure.length; i++) {
heights[i] = $toMeasure[i].offsetHeight;
}
var maxHeight = getMax(heights);
// check max of min-height's + padding for objects to set (if possible)
var minheights = [maxHeight];
try {
for (var i = minheights.length; i < $toResize.length; i++) {
var newMin = getOffsetMin($($toResize[i]));
if (!isNaN(newMin))
minheights[i] = newMin;
}
} catch(e) {}
maxHeight = getMax(minheights);
$toResize.each(function (i) {
var $this = $(this);
$this.css("height", (maxHeight - getVPaddingOffset($this)) + "px");
});
}
}
function setEqualHeight($toMeasureAndResize) {
setEqualHeight($toMeasureAndResize, $toMeasureAndResize);
}
function getMinHeight($object) {
return parseInt($object.css("min-height"), 10);
}
function getVPaddingOffset($object) {
var top = parseInt($object.css("padding-top"), 10);
var bottom = parseInt($object.css("padding-bottom"), 10);
return (top + bottom);
}
function getOffsetMin($object) {
return (getMinHeight($object) + getVPaddingOffset($object));
}
function getMax(nums) {
if (nums.length > 1) {
var newMax = nums[0];
for (var i = 0; i < nums.length; i++) {
newMax = Math.max(newMax, nums[i]);
}
return newMax;
} else if (nums.length == 1) {
return nums[0];
}
return 0; // error
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment