Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical alignment without knowing height in CSS?

Tags:

html

css

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?

like image 876
mike Avatar asked Nov 09 '10 17:11

mike


1 Answers

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%);
}
like image 160
Tom Avatar answered Sep 22 '22 09:09

Tom