0

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>

1 Answers1

2

This is caused by the body's default margin. And since your divs positioned relatively to the viewport, the margin of the body is increasing the height of viewport. (Thanks to Temani Afif for correcting)

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

Mohamed Ghulam
  • 457
  • 3
  • 7
  • Thank you very much! Why does `body` actually have a margin? – Three Year Old May 21 '22 at 17:24
  • 1
    The browser has some default styles it applies. CSS resets are used to remove and normalise these styles. – Ben Brookes May 21 '22 at 17:27
  • But what's the point of a margin on the `body`? – Three Year Old May 21 '22 at 17:31
  • 1
    @ThreeYearOld You're welcome, I am not 100% sure about the reason but most probably because if no CSS is applied the website should be readable, thats why there are default margins to the body, h tags, and so on. – Mohamed Ghulam May 21 '22 at 17:34
  • So no "content" would stick to the bottom of the page. Now I see. Thank you! – Three Year Old May 21 '22 at 17:42
  • 1
    @ThreeYearOld Exactly, nothing to stick to any side of the page, coz its applied to all 4 sides. – Mohamed Ghulam May 21 '22 at 17:44
  • 1
    *And since your divs are positioned absolutely to the body, the body's margin will also be calculated.* --> no correct because the element are positioned relatively to the viewport and not the body and the margin of the body is increasing the height of viewport (hence the scrollbar) – Temani Afif May 21 '22 at 18:04