Best way to center a <div> on a page vertically and horizontally?

J-Dog picture J-Dog · Dec 10, 2008 · Viewed 964k times · Source

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?

Answer

Vladimir Starkov picture Vladimir Starkov · Nov 13, 2012

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;
}
<div></div>