-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
  • 28,664
  • 7
  • 72
  • 132
Emil Woxen
  • 99
  • 1
  • 1
  • 8

2 Answers2

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
  • 28,664
  • 7
  • 72
  • 132
  • ah yes ofcourse - thank you. I find it odd, that i'm not able to center using Margin in a relative position though? – Emil Woxen 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
-1

I think it'll help you

.left, .right,.bottom,.top,.center{position: absolute;}
.display-container {width:400px;height:200px; background-color: grey;position: relative;}
.left{bottom: 0;left:0;}.right{right:0;top: 0;}.bottom{bottom:0;right:0;}.top{top:0;}.center{left:50%;top:50%;transform: translate(-50%,-50%);}
.hover {display:none;transition: all 1s;}
.display-container:hover .hover {display: block; transition: all 1s;}
<div class="display-container">
 <div class="center hover">
  Center
 </div>
  <div class="left hover">
  Left
 </div>
 <div class="right hover">
  Right
 </div>
 <div class="bottom hover">
  Bottom
 </div> 
 <div class="top hover">
  Top
 </div>
</div>
Weber
  • 73
  • 9