1

I want to center a div both horizontally and vertically using the method of using position absolute and left: -50% etc.

However, it will not become vertically centered, only horizontally.

The result is not centered vertically: enter image description here

Why?

http://jsfiddle.net/6cLwwrxc/

html

<div class="background">
  1<br>2<br>3<br>4<br>5<br>6<br>
  <div class="overlay">
    <div>foobar</div>
  </div>
</div>

css

.background
{
  border: 1px solid black;
  position: relative;
}

.overlay
{
  position: absolute;
  top: 50%;
  left: 50%;
}

.overlay > div
{
  background: #888;
  color: #fff;
  position: relative;
  top: -50%;
  left: -50%;
  padding: 10px;
}

If I use margin-top: -50% instead of top: -50% in .overlay > div, the foobar div moves too far upwards:

enter image description here

so apparently that height percentage is related to the background div.

Anders Lindén
  • 6,839
  • 11
  • 56
  • 109

1 Answers1

1

The calculation is not taking the height of the element being positioned into account. If you minus half the height from the direction of when it's being positioned from, you can get it centered.

http://codepen.io/anon/pen/jbbVpP

.overlay > div {
  background: #888;
  color: #fff;
  position: relative;
  top: -50%;
  left: -50%;
  padding: 10px;
  margin-top: -20px;
}

CSS Tricks has a good way of doing this with translate:

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
Paul Redmond
  • 3,276
  • 4
  • 32
  • 52
  • If I am using `transform` I get scrollbars as if the element was not transformed. There is a problem in that I cannot always use `overflow: hidden` to prevent that. – Anders Lindén Sep 11 '15 at 07:22