dole 0

Hi there

does anyone knows how can I center a div vertically and horizontally?

many thanks

5 answers

3
points
This was chosen as the best answer

You would use a container div that is set with the css display: table-cell, setting the height to the maximum height; Currently, only table cells can align blocks vertically. Then you would use the age-old block centering trick of margin: 0 auto; text-align: center on that same container div.

It might look something like this:

<div style="display: table-cell; height: 100%; width: 100%; margin: 0 auto; text-align: center">
<div>content</div>
</div>

Edit: Ironically, there was a linked item on Delicious today regarding this very topic (not my blog). Largely they use the margin and positioning tricks because IE6 doesn't support display: table or display: table-cell. I would read it too, but it all depends on the audience. Most people are dropping IE6 because the work required to support them with hacks like this, makes it difficult on designers to keep their code clean.

Answered over 9 years ago by Nathan DeGruchy
  • Just as an aside, my personal opinion is that the table-cell trick is an ugly hack. I would rather just approximate "vertical center" and work from there. Nathan DeGruchy over 9 years ago
1
point

For Firefox/Safari and other non-IE browses you can do the following:

set the width and height of the element you want to position in the center of the screen or parent element.

set position:absolute; top:0;bottom:0;left:0;right:0; margin:auto;

that will do it.

In IE you will need to use two surrounding divs. (hidden with conditional IE comments so that they remain invisible to all other browsers)

the outer div needs to have a margin-top:50% the inner child div needs to have a margin-top:-50%;

Answered over 9 years ago by Mark Malek
0
points
#iAmCentered {
    position:absolute;
    top:50%;
    left:50%;
    width:804px;
    height:578px;
    margin-left:-402px;
    margin-top:-289px;
}

Set the margin-left and margin-top to the half of the width / height of the element. Works with IE 6, too. Drawback : if the browser window is smaller than the element, one cannot scroll the entire element.

Answered over 9 years ago by Thomas Traub
ihsw 0
0
points

http://d-graff.de/fricca/center.html

Condition: the element being vertically centered must have a height (read: declared with the height property)

Interestingly it uses a float, and doesn't rely on positioning. Ever try to resize the height of the window of a browser to smaller than the element being vertically centered using absolute positioning? Try it. This method doesn't suffer from that problem.

Answered over 9 years ago by ihsw
Ismael 0
-1
points

Read the code if you don't understand the language.

This tutorial has some *hacks for IE6. Maybe it complements other answers.

http://rogeriolino.wordpress.com/2007/01/17/css-centralizar-horizontal-e-vertical/

Answered over 9 years ago by Ismael