Lieutenant Dan
Lieutenant Dan

Reputation: 8284

Center Horizontally and Vertically of page IE 6+

I'm trying to center 1 #div box with two small #divs inside of it, to be in the exact middle of the screen/page - ideally across all resolutions and IE 6 +, whats the best approach?

margin:0 auto; 

seems to do the trick horizontally, but what about vertically?

Upvotes: 1

Views: 948

Answers (2)

Jasper
Jasper

Reputation: 76003

If you know the size of the element you want to center, you can set the following CSS for it to center horizontally and vertically:

#centered {
    position   : absolute;
    left       : 50%;
    top        : 50%;
    width      : 150px;
    height     : 200px;
    margin     : -100px 0 0 -75px;/*set the left and top margins to the negative of half the element's width and height (respectively)*/
    background : #000;
}

Note that the parent of the element needs to have position set to something other than static:

#container {
    position : relative;
    width    : 100%;
    height   : 100%;
    border   : 1px solid #000;
}

Here is a jsfiddle: http://jsfiddle.net/jasper/rcN3P/

P.S. I checked and this works in I.E. 6.

Upvotes: 2

Michael
Michael

Reputation: 763

I just read this article on css-tricks about centering, it gives a interesting approach using pseudo elements, but you could just as easily add those elements into the markup instead (it wont be semantic but it will work).

http://css-tricks.com/14745-centering-in-the-unknown/

Upvotes: 0

Related Questions