Update: I have this post here for posterity, but you should probably just use flex-box in modern browsers.
Hopefully my next post won’t take as long… Anyway, here’s something new!
I recently updated and modified some jQuery code I threw together to equalize box element heights on a page. I’m working on a responsive design update for a website which required my code to be a bit more nimble. This solution differs a bit from the normal JavaScript solutions you’ll find around the web in that it re-evaluates the box height per row.
So, for example, if you had 9 divs with content and were displaying them 3 across, you would have 3 rows of divs. Now, if they all had very similar content height requirements, you could do a eval of all divs within a container or eval all divs with a certain class, grab the tallest one, and apply it to all.
It looks something like this (taken from this website)
function setEqualHeight(columns) {
var tallestColumn = 0;
columns.each(function() {
var currentHeight = $(this).height();
if(currentHeight > tallestColumn) {
tallestColumn = currentHeight;
}
});
columns.height(tallestColumn);
}
$(document).ready(function() {
setEqualHeight($(".container > div"));
});
Very simple and doesn’t use that much code. However, in my situation, I may have a box that is 300px high on the first row and the last row only needed to be 200px high for the tallest div. Its going to look rather odd to have all this extra padding that I don’t need on the last row of divs.
Enter a little function I call autosizeit. The way it works is by looking for any elements with the class “autosize”, getting the width of that class (they must all be the same width), then comparing that to the container size. It does this to determine how many elements will fit in a row. After that it will go through adding a blockX and rowX class to each element while recording the tallest one. Once it reaches the end of the row, it applies the height to the row and then resets the counters for the next one.
This also carries the advantage of being dynamic. If your container size is 100% and you have it resizing with your browser window, you just need to run the script again on a window re-size.
I use something like this:
$(window).resize(function() {
setTimeout(function() {
autosizeit();
}, 200);
});
I add a short delay so that it waits until you’ve finished re-sizing the window before running.
So where is this code? You can check it out here: Autosizeit on jsFiddle
Try changing the width of the .element class in the CSS box as well as adding boxes and content.
It could definitely be improved upon, but it works great for my use. For one, the autosize class is hard coded currently, so feel free to modify it and make it your own.
Enjoy.