dole 0

Hi there

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

many thanks

5 answers

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">

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 almost 10 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 almost 10 years ago

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 almost 10 years ago by Mark Malek
#iAmCentered {

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 almost 10 years ago by Thomas Traub
ihsw 0

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 almost 10 years ago by ihsw
Ismael 0

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

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

Answered almost 10 years ago by Ismael