CSS: center a DIV

#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:

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.

We use cookies to personalise content and ads, to provide social media features and to analyse our traffic. We also share information about your use of our site with our social media, advertising and analytics partners.OkRead more