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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With