For your given HTML and CSS, with the inner <div>
element set to position: absolute
, you are trying to vertically center a div that is taken out of the document flow.
You have a couple options for a solution.
Option 1.
You can set the inner <div>
to be position: relative
and that will allow it's parent <div>
to properly apply the behavior of align-items: center
to the inner <div>
(because the default flex-direction
is row
). Then you can absolutely position content within the inner div if needed. codepen.io flex example
CSS
.container {
align-items: center;
background-color: #888;
display: flex;
height: 100vh;
width: 100%;
}
.inner {
background-color: #fff;
height: 100px;
position: relative;
width: 100px;
}
HTML
<div class="container">
<div class="inner"></div>
</div>
Option 2.
If you truly need the inner <div>
to be position: absolute
, then you can set position: relative
on the parent <div>
element, then set a top
and transform: translateY()
on the inner <div>
. codepen.io position:absolute example
CSS
// display: flex and align-items: center
// are not needed to vertically align
// an element that is absolutely
// positioned
.container {
// align-items: center;
background-color: #888;
// display: flex;
height: 100vh;
position: relative;
width: 100%;
}
.inner {
background-color: #fff;
left: 0;
height: 100px;
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100px;
}
HTML
<div class="container">
<div class="inner"></div>
</div>