Don’t let images screw up your baseline grid!

I like to joke about being obsessed with getting everything to line up, always. It might not be a joke…

I’m not sure if this is the right thing to do, but I do it anyway, because it gives me immense pleasure to see the results. I’ve been told I’m just plain wrong for even considering it, but a little while ago I decided I can’t let variable height images screw up my baseline flow. So I got some help from the internet, Dan Neame, and my fantastic co-worker Señor Magnus Holmes, and we came up with this atrocity:

$(window).resize(function() {
	var lineHeight = parseInt($('body').css('line-height'),0);
	$('.baseline').each(function() {
		var closest = ($(this).height() / lineHeight) | 0,
		bottomMargin = (closest*lineHeight) - $(this).height() + lineHeight;
		$(this).css('margin-bottom', bottomMargin);
	});
});
$('.baseline').load(function() { $(window).resize(); });

Now all you have to do is add the class “baseline” to any element you need to respect the baseline flow, and problem solved!

Now, I am pretty sure it’d be a very bad idea to do this on hundreds of elements at once, but if you’re having a few problems getting things to line up, this is a decent solution. In fact, I use it on the lead text on this very post, to prevent the odd line-height to mess up my groove. I’m sure there are smoother ways to do this, and I’d love to hear what your suggestions on how to improve this! Tweet!

Comments? Tweet me!