Best way to center a <div>
element on a page both vertically and horizontally?
I know that margin-left: auto; margin-right: auto;
will center on the horizontal, but what is the best way to do it vertically, too?
30 s
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;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div></div>