Saturday, April 2, 2011

Container centered horizontally and vertically using CSS

Position absolute plus mathematical computations

In this approach you will learn how to position your container centered. Horizontally and Vertically? Yes, using the position absolute plus some mathematical computations.

Insert the code below inside your <body> ... </body>

<!-- Center -->
<div class="centered ab">
</div>
<!-- Center -->

Create center.css, then input the CSS code below:

/********************************************
Coded by: alfieindesigns
Website: http://alfie-css.blogspot.com/
Inquiries: alfienollora@yahoo.com
********************************************/

/**********************
COMMON STYLE
**********************/
.ab {position:absolute;}

/**********************
CENTERED CONTAINER
**********************/
.centered {
background:#000;
width:20px;
height:20px;
top:50%;
left:50%;
margin:-10px 0 0 -10px;
}

On the <head> tag insert the code below: (make sure path is correct "css/") i put my tab.css on css folder.

<link rel="stylesheet" type="text/css" href="css/center.css" />

The computations

Make sure to put width and height to ensure that our computation will work properly. Below you will notice that the top and left are sets as 50%, we used percentage (%) instead of px. Why? because percentage computed the resolution/size of you window screen while the px is set as fixed.

/**********************
CENTERED CONTAINER
**********************/
.centered {
background:#000;
width:20px;
height:20px;
top:50%;
left:50%;
margin:-10px 0 0 -10px;
}

Top 50% is concerning the value of height, likewise left is the value of width.

width:20px;
height:20px;
top:50%;
left:50%;

We need to set negative value on margin half the whole value of width or height. Example:

height:500px;
top:50%;
margin-top:-250px;

The sample above will make abolute 'div' vertically centered.

On our css we used width 20px, height 20px, so the margin will be negative half value of the two, so:

width:20px;
height:20px;
top:50%;
left:50%;
margin:-10px 0 0 -10px;

That's all! Enjoy! God bless always!

2 comments:

  1. hmmm i see, margin: 0px auto to make it center

    Legal Software Singapore

    ReplyDelete
    Replies
    1. Yea, but that's for horizontal centered only. And make sure it's a block element. Thanks

      Delete