How to center a DIV with unknown size horizontaly and vertically on screen

alignment, css, html, layout

Solution

You can vertically center a box with an unknown height with the help of css tables. The height of the box is determined by its contents. See this demo that uses the position: fixed property for the box. The box's width is set as well.

And this is the workaround for IE <= 7:

#table {
  height:100%;
  text-align:center;
  white-space: nowrap;
}
#container {
  display: inline;
  zoom: 1;
  text-align: left;
  vertical-align: middle;
}
#IEcenter {
  height: 100%;
  width: 1px;
  display: inline;
  zoom: 1;
  vertical-align: middle;
}
#container * {
  white-space: normal;
}

Does this meet your requirements?

Problem

I need to center a DIV on center off screen, both horizontally and vertically, I don't know the DIV size, and the div is `position:fixed;`. This negative margin trick does not work, because I don't know the div size. `top:50%; left:50%; magin-top:-100; margin-left:-100;` The `margin-left: auto; margin-right: auto;` does not work because doesn't work with `position:fixed;` and `margin-top:auto; margin-bottom:auto;` also does not vertically center; I found that this method: `display: table-cell; vertical-align: middle;` don't work ether; I know how to do this with JavaScript using getComputedStyle to get the div content size, and do the math to fix it position, but I want a pure CSS solution, because I don't want to trigger a JS every time my div content changes.

Original source