2

To horizontally center an element, one sets width to x, left to 50% and margin-left to -x/2. This works perfectly with x = 50 % (see example below). Why does it not work for vertical centering? The example below does not work.

div.myDiv {
    width: 50%;
    height: 50%;
    left: 50%;
    top: 50%;
    margin-left: -25%;
    margin-top: -25%;
    position: absolute;
    border: 1px solid #555;
}
<div class="myDiv">I'm a div</div>

Tested in FF10 and IE8 with HTML 4.01 Transitional and only one div-tag in the body-section.

3 Answers3

1

You don't have fixed width and height (fluid). So you can't make the div in center vertically just using the CSS you mentioned in your post. You need to go with javascript or jQuery to achieve that. I have done this before, so I am just linking it here. https://stackoverflow.com/a/15293191/1577396


As specified in W3C, the margin properties including margin-top and margin-bottom refers the width of the containing block (not the height), if set in percentages.

So, you can't align a fluid container vertically using margin-top and margin-bottom as the case in fixed dimension container.

Community
  • 1
  • 1
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • Thanks. I thought so, but why is not possible? And why do both IE and FF support it for horizontal centering but not for vertical centering? – user1904159 Mar 13 '13 at 15:30
  • @user1904159 the margin values always refer to the width of the containing block if set in `percentages`. So, not possible to verical aligning as the `margin-top` and `margin-bottom` should consider `height` inspite. check this link http://www.w3.org/TR/CSS2/box.html#margin-properties – Mr_Green Mar 13 '13 at 16:55
  • Thank you! Very helpful. :) Sorry for the late reply. – user1904159 Mar 18 '13 at 10:39
0

Vertical centering can be done in css playing with display: table-cell or fiddling with line-height - just a starting point for you to play with

Luca
  • 9,259
  • 5
  • 46
  • 59
-1

Try this:

div.myDiv {
margin: 0 auto;
}

auto will get you the horizontal centering you are looking for OR you can just set auto for the entire myDiv to get both vertical and horizontal centering.

div.myDiv {
margin:auto;
}
user763460
  • 221
  • 2
  • 8
  • 18