Center an Element Horizontally and Vertically

Saturday, August 27th, 2011 | CSS, HTML | 0 comments

This one is an oldie but a goody. Using basic HTML/CSS we can position an element directly in the center of the page. Here are the steps to perfectly centering an element:

  1. Absolutely position the element
  2. Position the element 50% from the top, 50% from the left
  3. Define the width/height of the element you wish to center
  4. Compensate for the image’s width and height by applying two negative margins: A negative left margin set to half of the image’s width, and a negative top margin set to half of the image’s height.
#center-me {
	position: absolute;
	left: 50%;
	top: 50%;
	width: 600px;
	height: 260px;
	margin-left: -300px;
	margin-top: -130px;
	background: url('../images/holy-crap-centered.gif') no-repeat;
}
View Demo

 

Heyyyyy, Leave A Comment!

Submit