One of the biggest short comings of modern HTML/CSS is the inability to reliably vertically center certain elements. A quick Google search will reveal almost a dozen or so tricks (or better yet – “hacks”) to vertically center things. Most of the tricks involve setting table properties on non-table items, getting sneaky with negative margins, or positioning things absolutely.
All these approaches you will find on Google do work in certain use cases. The problem is they don’t work reliably in your scenario unless the stars align.
With that said, instead of trying to do black magic with CSS, sometimes it’s better to just fire up javascript and let it do the job. Using javascript to center things vertically could be seen as overkill, but the harsh truth is right now it’s simply more reliable.
(function ($) { | |
$.fn.verticalAlign = function() { | |
return this.each(function(i){ | |
var ah = $(this).height(); | |
var ph = $(this).parent().height(); | |
var mh = Math.ceil((ph-ah) / 2); | |
$(this).css('margin-top', mh); | |
}); | |
}; | |
})(jQuery); | |
jQuery(document).ready(function($){ | |
// If the size of the parent item depends on images loading we | |
// need to fire after the page has loaded, that way the elements | |
// size is finalized, giving us the correct information. | |
// Use https://github.com/desandro/imagesloaded | |
$('#container').imagesLoaded( function() { | |
$(".caption").verticalAlign(); | |
}); | |
$( window ).resize(function() { | |
$(".caption").verticalAlign(); | |
}); | |
}); |