How to position DIV at the center of web

- Wednesday, April 07, 2010

When Web 2.0 was introduced and web designers started using DIV/CSS to build their website, as websites written using DIV/CSS are considered to be load faster and coded cleaner while TABLES can increase page weight. Soon the TABLE based designs started fading out. Now every major website you see on internet are DIV based layout with CSS. DIV/CSS based layouts are highly effective for two and three-column designs and we can achieve the same table-based layout effects, reducing markup code, get faster page downloads.

How to position DIV at the center of web

Many web designers find it difficult to align the DIV in the center of the web page, because DIV's are 100% in width by default. We can overcome this situation by using CSS or JavaScript.

There are two ways to place a DIV at the center of a web page, JavaScript and CSS.

JavaScript: If you want to position a DIV at the center of a web page using JavaScript, use the following JavaScript code:

<div id="cDIV" style="position: absolute;
left:expression(document.body.clientWidth/2-cDIV.offsetWidth/2);
top:expression(document.body.clientHeight/2-cDIV.offsetHeight/2)">
Your DIV will appear at the center and middle of the page,
vertical and horizontal. </div>

CSS: CSS can come in handy when dealing with multiple browser issues or JavaScript disabled/blocked in browsers.

<style type="text/css">
#cDIV {
position: absolute;
width: 756px; /*define the width of the DIV*/
height: 356px; /*define the height of the DIV*/
top: 50%; /*for vertical alignment*/
left: 50%; /*for vertical alignment*/
margin-right: auto; /*for horizontal alignment*/
margin-left: auto; /*for horizontal alignment*/
margin-top: -178px; /*always take 1/2 from the 
size of the height of your DIV, it has to be in negative*/
margin-left: -378px; /*always take 1/2 from the 
size of the width of your DIV, it has to be in negative*/
} 
</style>

<div id="cDIV"> Your DIV will appear at the center and 
middle of the page, vertical and horizontal. </div>

Please try these codes and let me know by commenting on this blog if it was helpful for you.

Joydeep Deb

Marketing . Innovation . Technology

Share:

About the Author
Joydeep Deb

Joydeep Deb is a Senior Digital Marketer and Project Manager with strong experience in Digital Marketing, Lead Generation, Online Brand Management, Marketing Campaigns, Project Management, Search Engine Optimization (SEO), Search Engine Marketing (SEM), PPC, eMail Marketing, Web Analytics, Web Technologies, Web Design and Development.

With an MBA in Marketing. IIM Calcutta Alumini. Lives in Bangalore, Karnataka - India.

Get social with Joydeep at Twitter | Facebook | LinkedIn

Subscribe to Newsletter

Receive my latest posts right in your inbox? Enter your email address below to subscribe.

We'll never share your email with anyone else.