Best way to center a on a page vertically and horizontally? [duplicate]

The best and most flexible way

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;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;

Leave a Comment