Why are these centered divs shifted upwards and how to fix this?

I don’t understand why these two divs are shifted upwards. How can I align them neatly to the center of the viewport? margin does not seem to be a suitable method to me. Thank you!

body {
  background: linear-gradient(black 50%, grey 50%);
  height: 100vh;
}

div#center-upper-half {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -100%);
  background: red;
  width: 200px;
  height: 200px;
}

div#center-lower-half {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, 0);
  background: green;
  width: 200px;
  height: 200px;
}
<div id="center-upper-half"></div>
<div id="center-lower-half"></div>

>Solution :

This is caused by the body’s default margin.
And since your divs are positioned absolutely to the body, the body’s margin will also be calculated.

Solution 1:

Remove the body margin and it should line up perfectly:

body {
  background: linear-gradient(black 50%, grey 50%);
  height: 100vh;
  margin: 0;
}

Solution 2

If you dont want to change the body’s margin, you need to wrap your divs with a container div and give it the following:

.container {
  position: relative;
  height: 100%;
}

Output:

enter image description here

Leave a Reply