I would normally use absolute positioning and set the top to 50% with a negative margin-top (half of the child's height) to center vertically. In this case that will not work because the child element's height will vary.
So is there a way to vertically center a div within a div without knowing the child's height?
The following jquery function centers vertically assuming the item you are positioning is already position absolute and the parent position relative
$.fn.vAlign = function () {
return this.each(function () {
$(this).css('top', '50%').css('margin-top', -Math.ceil($(this).height() / 2) + "px");
});
};
View in action - http://jsfiddle.net/vqbMU/2/
UPDATE:
A pure CSS solution for browsers supporting css transforms (IE9+) http://caniuse.com/#search=transform
.align-v {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With