Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I center vertically and horizontally a div inside the body element without absolute positioning? [duplicate]

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.

like image 892
circuitlego Avatar asked Nov 29 '22 16:11

circuitlego


1 Answers

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>
like image 200
Daniel Imms Avatar answered Jan 31 '23 00:01

Daniel Imms