Vertical Centering with CSS

With a little help from Javascript

It is next-to-impossible to center vertically using pure CSS. There are many solutions, but all of them have some limitations or require complicated markup (one for IE, another for the other browsers). I prefer to keep it simple.

Let's see if I can get this to work:

Right

1

2

Left

1

2

3

4

Value 1
Value 2

The cyan patch is the element's original position before I shifted it. Are Value 1 and Value 2 vertically in the middle?

(Note that none of the elements have an explicit height. Most solutions require at least an explicit height/margin somewhere.)

It works in IE, but not in other browsers. According to the CSS specs, it will not work because the container (denoted by the cyan patch) does not have a known height, so we cannot specify the position using percentage. IMO, IE got it right. This should work.

jQuery to the rescue

We can use jQuery to set the height, but if we are going to use jQuery, we might as well remove the boilerplate code and center the element directly:

Right

1

2

Left

1

2

3

4

Value 1
Value 2

Perfectly centered all the time, as long as you have Javascript enabled.

Resizing

Note that the positioning is done just once. If the container is resized, it will not be centered again. After resizing the left column:

Right

1

2

Left

1

2

3

4

Value 1
Value 2

The easiest way to auto-center is to use the original boilerplate code and use jQuery to assign container's own height to itself:

Right

1

2

Left

1

2

3

4

Value 1
Value 2

(Shouldn't the container know its own height? That's why I say IE got it right — the container has the contained height if its height is not specified.)

The browser will then keep the element auto-centered for us. Perfect!

The catch

You absolutely need Javascript to be enabled. If not, the element will be mis-positioned. Currently, FireFox and Opera leaves the y position untouched, so the element is just a little off. Chrome and Safari flings element way out of place. I have no idea what height they are referencing.

Catch #2

You can only get the correct height for visible elements — you cannot manipulate hidden elements.