I wanted to centre a small content in the page both vertically and horizontally. It’s simple using position but I had a night mare of making it work on IE 7. To stay on safer side I didn’t want any approach that involves use of position.

Table is designed to center the

( Standard cells ) of the table-row’s total width. Which makes it easy to get the magic done without having to write many styles.

I'm centered :)

That was simple indeed. To achieve the same in ultra modern fashion we need to use 3 div‘s with combination of CSS property.

The first or the outer div will make up the table or the container with display:table. The second one or the middle one will form the Standard cell, with display:table-cell and at the end the inner one is the play ground, it will be centered no matter the style provided to it. Unless you mess it with Position or float.

HTML

I'm Centered

The CSS

.main-container{
	display: table;
	height: 100%;
	width: 100%;
}
.container-wrap{
	display: table-cell;
	vertical-align: middle;
}
.playground{
/* For styling only */
	height: 100px;
	line-height: 100px;
	margin: 0 auto;
	text-align: center;
	width: 500px;
}

That is it, now you have a centered object which can take more styles :). This is just one of the many way to achieve centered object.

I AM Centered

Additional

#main-container assumes the container its wrapped in covers the entire screen, if not it will centre the container inside respective to the dimensions of its container.

If you plan to use this directly you can set html, body a width and height of 100%.

html, body{
 height:100%;
 body: 100%;
}

Thats a bit of cheat, the cleaner option is to wrap the entire setup in a wrap that covers entire screen.

I'm Centered
.main-container-wrap{
    height: 100%;
    width: 100%;
    position: absolute;
}
.main-container{
	display: table;
	height: 100%;
	width: 100%;
}
.container-wrap{
	display: table-cell;
	vertical-align: middle;
}
.playground{
/* For styling only */
	height: 100px;
	line-height: 100px;
	margin: 0 auto;
	text-align: center;
	width: 500px;
}

Note For the demo I have used some tweaks to make the following work with Techstream’s Demo template, the are described in demo.css as comments.

Demo
Download