5

I have read countless Q&A's and blog posts about vertically aligning and centering divs, but I cannot get the simplest case to work: an empty 20x20 div directly in the html body.

html:

 body
    {
        background-color:DarkGray;
        display:table;
    } 

    .box
    {
        background-color:black;

        display:table-cell
        margin:0, auto;    
        
        width:20px;
        height:20px;
    }
<body>
    <div class="box">
    </div>
</body>

 
   

Here is the JSFiddle.

Nemus
  • 3,879
  • 12
  • 38
  • 57
circuitlego
  • 3,469
  • 5
  • 22
  • 22

2 Answers2

21

display:table and display:table-cell are bad, stay away from them. Here is a very common way to center a div inside <body>. It positions the element's top and left sides at the 50% point within body and then subtract 1/2 the width and height from the margin-top and margin-left.

.box {
  background-color: black;
  position: absolute;
  left: 50%;
  top: 50%;
  width: 20px;
  height: 20px;
  margin-left: -10px;
  /* -1/2 width */
  margin-top: -10px;
  /* -1/2 height */
}
<body>
  <div class="box">

  </div>
</body>
dota2pro
  • 7,220
  • 7
  • 44
  • 79
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
  • 2
    Because you can do everything without them, they were designed to be used for table cells only. One thing that they can do which I don't think you can do without them is center multiple lines of text vertically. – Daniel Imms Mar 10 '13 at 13:08
2

First, there is a syntax error in margin style:

margin: 0, auto;

But should be:

margin: 0 auto;

With support of vertical positioning it should be:

html,
body {
  background-color: DarkGray;
  height: 100%;
}

.box {
  position: relative;
  top: 50%;
  margin: -10px auto;
  /* -height/2 */
  width: 20px;
  height: 20px;
  background-color: black;
}
<body>
  <div class="box">
  </div>
</body>

And there is a discussion on this site Why not use tables for layout in HTML?

dota2pro
  • 7,220
  • 7
  • 44
  • 79
Olexander Ivanitskyi
  • 2,202
  • 17
  • 32