CSS: center a DIV

If you need to center a DIV you can use the following CSS code:

#mydivid {
position:absolute;  /* to be able to set the position within the containing div (from left and top) */
left:50%; /* start at 50% of the parent div */
top:50%; /* start at 50% of the parent div */
width: XXXpx; /* only works with fixed width divs since you need to divide by 2 below */
height: YYYpx; /* only works with fixed height divs since you need to divide by 2 below */
margin-left:-xxxpx; /* xxx = -XXX/2 : moving the center to the right position */
margin-top:-yyypx; /* yyy = -YYY/2 : moving the center to the right position */
}

Note that absolute positioning means positioning relatively to lowest parent in the hierarchy with a position attribute not equal to static. If all parents have position: static (or no position:xxx) then it will position relatively to the <body> element.

An alternative to position: absolute is position: relative. This means that the position defined is relative to the position, the element should have had (if it had position: static). This means it will be relative to the parent if its parent as no children before it with position:static. If it has siblings preceding it with position: static, it will not be centered properly (of course you can then define the siblings after this element to solve the problem).

If you want to center it on the page and give it a fixed position (i.e. it will not move while scrolling), you should replace:

position:absolute

by:

position:fixed

If what you’re centering is a background image, you can use either:

body {
background: url(background.png) center center no-repeat;
width: 100%;
height: 100%;
}

or:

body {
background-image: url(background.png);
background-repeat: no-repeat;
background-position: 50% 50%
}

If you want the background image to always be displayed at the same position (kind of like a watermark), you can just add the following:

background-attachment: fixed;

3 thoughts on “CSS: center a DIV

  1. Hi,

    the frist css (center div) will work only in case your container is also positioned (because of position:absolute).
    If you change the position to “relative” it works also for such cases.

    cheers
    Alex

    1. I’ve added a note that position:absolute will position relatively to the last positioned parent or to body if none are there.
      Also position:relative will position relatively to the parent in most cases but not if preceding statically positioned siblings exist.

Leave a Reply

Your email address will not be published. Required fields are marked *