-1

I thought it was possible to center a div vertically within another div with its position set to relative? I'm not a fan of position absolute, as it layers it on top of everything.

What am i missing here? It can be centeret horizontal no problem.

.main_container {
  position: relative;
  height: 100vh;
  width: 100vw;
}

.main_container .inner_container {
  position relative;
  height: 90%;
  width: 95%;
  margin: auto;
}
<div class="main_container">
  <div class="inner_container">
    //Some content here, img and text etc.
  </div>
</div>
Richard Deeming
  • 29,830
  • 10
  • 79
  • 151
Emil
  • 125
  • 1
  • 2
  • 10

1 Answers1

2

Use Flexbox instead of relative positioning:

.main_container {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

.main_container .inner_container {
  height: 50%;
  width: 50%;
  outline: 1px dotted black;
}

html, body {
  margin: 0;
  padding: 0;
}
<div class="main_container">
  <div class="inner_container">
    //Some content here, img and text etc.
  </div>
</div>
Richard Deeming
  • 29,830
  • 10
  • 79
  • 151
  • ah yes ofcourse - thank you. I find it odd, that i'm not able to center using Margin in a relative position though? – Emil Jan 11 '22 at 11:55
  • Prior to flexbox, vertical centering in CSS was painful. Using `auto` for vertical margins would compute as `0` - see [this answer](https://stackoverflow.com/a/12417336/124386) for more details. – Richard Deeming Jan 11 '22 at 11:58
  • it would be good to help us close this million-th duplicate. I am pretty sure you know a lot of centering question around. – Temani Afif Jan 11 '22 at 12:02