Wednesday 1 May 2013

Horizontal Centering of a div


Centering a div horizontally means placing the div in the center of the parent div in horizontal direction. This can be done in many ways. One of the simple and commonly used method is explained below.

Sample Code:

<html>
<head>
<style>
#horizontal{
height:100px;
width:100px;
background-color: Yellow;
position: relative;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<div id="horizontal">
Horizontally centered div
</div>
</body>
</html>

Code Explained:

Setting margin-left and margin-right to auto is important for this horizontal centering of the div named "horizontal". Here the parent of "horizontal" div is body of the page. "horizontal" div is placed in the horizontal center of the body of the page.

                       There are few important things to note here. The position of the div should be relative to the parent because the div is placed in the center of the parent element relatively. Secondly width of the div should be specified. If width of the div is not specified the div assumes complete width of the parent .  If the div has the same width of the parent element then its automatically aligned at the center and it would be meaning less to set margin-left and margin-right to auto.
Perfectly placed at the center of body

When the div assumes the width of the parent

When the position of the div is absolute


Post your doubts and suggestions in the comments below

No comments:

Post a Comment