Online Portfolio and Resource Blog Online Portfolio and Resource Blog


CSS: Centering a Div Vertically

13Dec 2011

In order to vertically center a block level element, we need to give it an absolute position. This will detach the element from its surroundings and will allow us to give it a specific position related to the browser window.

By offsetting the div by 50% from the top and left, we are positioning upper-left corner to the center of the page. The last step is to move the div to the left and top by using half of its dimensions in a negative margin.

For example, if the width of the element is 960px, then set the left margin to -480px. If the height of the element is 600px, then set the top margin to -300px.

HTML Structure

<div id="main">
  <div id="header"> Header </div>
  <div id="content"> content </div>
</div>

CSS

body {
	background: url("bg.gif");
	font-family: Arial, Verdana, sans-serif;
}
#main {
	width: 960px;
	height: 400px;
	background: #f1f1f1;
	text-align: left;
	position: absolute;
	top: 50%;
	left: 50%;
	margin: -200px 0 0 -480px;
}
#header {
	background: #000;
	padding: 10px;
	color: #fff;
}
#content {
	padding: 10px;
}

Click here for the final result

Related Article: CSS: Center a Div Using Absolute Positioning

Leave a Reply