CSS TRICK: Positioning with negative margin

5 08 2006

The following examples show how to set an object in an absolute position anchored at the center of the screen.

It’s very useful because if the size of the user screen changes the site is shown in the same way each time.

EXAMPLE:

To make this I’ve written these lines:

div #myBox
{
position: absolute;
top: 50%;
left: 50%;
width: 420px;
height: 240px;
margin: -210px 0 0 -120px;
}

This is the code that postions a DIV exactly at the center of the screen.

Explanation:

The DIV is positioned with the top left corner in the real center of the screen by the instructions top : 50% ; left : 50% ;

But now the DIV is not at the center it is something like this:

positioned on center of the screen

With the instruction margin : -210px 0 0 -120px ; we tell the browser to move the DIV by half of its width and height in negative directions.Et voilà the final result:

box on the center of the screen

ANOTHER EXAMPLE:

If you want to put an image over the top left corner of the div you should write this:

img #redBall
{
position: absolute;
top: 50%;
left: 50%;
margin: -260px 0 0 -150px;
}

It’s quite simple, but you must pay attention to the size of every object and its margin. Here is the result:

clip_image008.gif


Actions

Informations

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>