Wednesday 1 May 2013

Vertical and Horizontal centering of a div


Centering a div horizontally means placing the div in the center of the parent div in vertical direction. 


Sample Code :

<html>
<head>
<style>
#vertical{
  position:relative;
width:120px;
height:100px;
top:50%;
left:50%;
margin:-50px 0 0 -60px;
background-color: yellow;
}
</style>
</head>
<body>
<div id="vertical">
Vertically centered div
</div>
</body>
</html>

Code Explained :

top: 50% is setting the div at a distance of 50% of the parent div height from the top. 
left:50% is setting the div at a distance of 50% of the parent div width from the left.
margin: -50px 0 0 -60px is setting the div at -50px from the top of the parent div and -60px from left of the parent div. We have chose -50px and -60px as they are half the height and width of the div respectively. 

Setting -[negative]px implies that setting the div in the opposite direction. In the above example setting -50px from top means lifting the div 50px in the top direction.

margin:[top] [right] [bottom] [left] is the format. All the margins can be set in a single line.

Position should be specified. Height and Width should be specified.






Post your doubts and suggestions in the comment below

No comments:

Post a Comment