IMG-LOGO

How to center a div vertically and horizontally in CSS?

andy - 08 Jul, 2013 4368 Views 0 Comment

In this tutorial, you will learn how to center a div vertically and horizontall in css.

It is actually pretty easy to do, what you need to remember is to apply two properties of css which are display:table-cell and text-align:center. Remember that display:table-cell does not work in IE 7 and below, so we have to use a hack. Remember to include text-align:left to normalise the text-align behaviour inside the object that you want to center.

This is how the sample html code will look like:
<div id="outer">
    <div id="inner">
    	<div id="boxinside">Enter the content in here...</div>
    </div>
</div>
This is will be the css code:
/**** Remember to  apply vertical-align to middle ****/
#outer{
	width:600px;
	height:500px;
	background:#FF9;
	position:relative;
	vertical-align:middle;
	display:table-cell;
}

#inner{
	width:100%;
	text-align:center;
}

/**** Remember to apply the auto margin and text-align to left ****/
#boxinside{
	width:150px;
	height:150px;
	margin:0 auto;
	background:#666;
        text-align:left;
        color:#ffffff;
}

/**** HACK FOR IE 6 and 7 ****/
#inner{
	*position:absolute;
	*top:50%;
}

#boxinside{
	*top:-50%;
	*position:relative;
}
/**** END HACK FOR IE 6 and 7 ****/

Quick Demo

Enter the content in here...

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to style pagination links with CSS?

Do you need to create a beautiful, simple and elegant pagination links with css? Simply follow our easy and quick tutorial on how to create the pagination links easily with CSS.

Optimizing your site for printing

The easy way to optimize your site for printing is to create a separated external css targeting a media to print only When a printing action is being executed the browser will send over the information from your page to ...