The best and most flexible way
My demo on dabblet.com
The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto
is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top
and bottom
(does not work in IE7).
This trick will work with any sizes of div
.
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}