Bits & Bytes

Centering HTML Elements with CSS Absolute Positioning

Here, we have a medium gray, outer div element with a lighter gray div inside it. The inner div is 300 pixels by 250 pixels and has a 5 pixel wide border with a padding width of 10 pixels. So, the inner div is 2*5 + 2*10 + 300 = 330 pixels wide and 2*5 + 2*10 + 250 = 280 pixels high. The outer div has a 30 pixel margin around it for presentation.

(Proverbs 20:1-4) Wine is a luxurious thing, and drunkenness riotous: whosoever is delighted therewith shall not be wise. As the roaring of a lion, so also is the dread of a king: he that provoketh him, sinneth against his own soul. It is an honour for a man to separate himself from quarrels: but all fools are meddling with reproaches. Because of the cold the sluggard would not plough: he shall beg therefore in the summer, and it shall not be given him.

To center a block element both vertically and horizontally within another element, we use negative margins. However, first we set the left and top positions at 50%. This places the upper-left corner of the inner div in the center of the outer div. To correct this placement and put the center of the inner div in the center of the outer div, we use a negative margin that is half the size of the inner div in both the horizontal and vertical directions. These values are 330/2 = 165 and 280/2 = 140, respectively. So, the left and top margins are set to -165px and -140px. The HTML and CSS to create the effect above is shown below.


<div style="position:absolute; width:480px; height:360px; background-color:#aaaaaa; margin:30px;">

<div style="position:absolute; background-color:#DDDDDD; width:300px; height:250px; padding:10px; border:5px solid #444444; left:50%; top:50%; margin-left:-165px; margin-top:-140px;">

<p>(Proverbs 20:1-4) Wine is a luxurious thing, and drunkenness riotous: whosoever is delighted therewith shall not be wise. As the roaring of a lion, so also is the dread of a king: he that provoketh him, sinneth against his own soul. It is an honour for a man to separate himself from quarrels: but all fools are meddling with reproaches. Because of the cold the sluggard would not plough: he shall beg therefore in the summer, and it shall not be given him. </p>

</div>

</div>

Tags: , , , , , , , , ,

Michael Hall

By: Michael Hall

Leave a Reply

*

 

© 2007–2024 XoaX.net LLC. All rights reserved.