5

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?

FR6
  • 3,157
  • 3
  • 24
  • 28
mike
  • 8,041
  • 19
  • 53
  • 68

4 Answers4

5

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%);
}
Tom
  • 12,591
  • 13
  • 72
  • 112
3

You can make the element display: table-cell and put vertical-align:center. I don't usually recommend using display: table- but that's the easiest solution I think

marioBonales
  • 91
  • 2
  • 6
1

You can also grab the child's height easily enough with JavaScript dynamically, and even easier with a JS library like jQuery.

According to your profile, you do have some familiarity with jQuery, so I would suggest that route. If you need help with that solution let me know.

Betard Fooser
  • 526
  • 5
  • 14
0

Use padding top , padding bottom to center elements vertically , with or without height definitions ...

Conex
  • 832
  • 8
  • 17
  • I don't think padding will work if the height of the element changes, the only CSS solution is to use table-cell, or you can use javascript – Tom Oct 20 '11 at 16:59
  • Using the display:table-cell solution still uses div's, see http://blog.themeforest.net/tutorials/vertical-centering-with-css/ – Tom Nov 01 '11 at 12:38