Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Responsive equal height divs and other HTML elements with jQuery. Ready to use out-of-the-box. // FEATURES: Automatically checks for row ends, so no need for classes like "last" for the last element of a row // Supports multiple classes that can be set. // Resizing can be cancelled simply by adding the class "noresize" to an element (added for c…
/*
Usage:
<div class="equal-height">
<div class="resize-me">Stuff</div>
<div class="resize-me">Stuff</div>
<div class="resize-me">Stuff</div>
<div class="resize-me">Stuff</div>
</div>
<script src="equal-height.js"></script>
<script>
$(document).ready(function() {
resize();
});
</script>
*/
// Go through all the equal-height -wrappers and elements to resize,
// calculate the tallest elements and fire up doResize() to resize them.
function resize() {
// List of classes to resize
var resizeThese = [
"resize-me",
"resize-example2"
];
// Find the equal-height divs
$(".equal-height").each(function() {
var $equal-height = $(this);
// Loop through all the classes to be resized
for (var i = 0; i < resizeThese.length; i++) {
// Set the current class to be resized
var currentClass = resizeThese[i],
tallest = 0,
divs = [],
lastpos,
curpos,
first = 0;
// Reset element heights
resetResize(currentClass);
// Get elements matching currentClass from inside equal-height wrapper
$equal-height.find(currentClass).each(function() {
// Dont resize if element has noresize-class
if(!$(this).hasClass("noresize")) {
// Get element position
curpos = $(this).position().top;
// If first element, set lastpos
if(first == 0) {
lastpos = curpos;
first = 1;
}
// If the Y-position is different from lastpos, add a clear and doResize() the row
if(lastpos != curpos) {
doResize(divs, tallest);
$(this).css("clear", "both");
lastpos = $(this).position().top;
tallest = 0;
divs = [];
}
tallest = Math.max(tallest, $(this).height());
divs.push($(this));
}
});
// Call doResize() for the last row of elements
doResize(divs, tallest);
}
});
}
// Reset element heights
function resetResize(currentClass) {
$(currentClass).height("auto");
}
// Resize a bunch of elements
function doResize(divs, tallest) {
for(i = 0; i < divs.tallest; i++) {
divs[i].height(tallest);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.