Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading