Centering elements both Horizontally & Vertically

An element can be easily horizontally centered using margin:0 auto properties. To make it vertically centered more works are needed to be done.

Lets say we have a markup  like following having a div with id Body. Its going to be centered.

 <body> 
  <div id="body"> 
    Content goes here 
  </div> 
</body>

CSS Code:


 html,
 body {
 width:100%;
 height:100%;
 }
 html {display:table;}
 body {
 display:table-cell;
 vertical-align:middle;
 }
 #body {
 max-width:50em;
 margin:0 auto;
 }
 

Here, we made the HTML to behave like a table and body as a inner cell of the table. So saying vertical-align:middle makes everything inside body vertically centered.
More explanation can be found in 456bereastreet.com

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s