B M B M - 27 days ago 9
HTML Question

CSS: flexbox container with top & center aligned divs

I am trying to create a layout with top and center aligned

div
s.

flexbox layout

It does work, kinda: https://jsfiddle.net/zeo29uLa/

<div class="flexbox-container">
<div class="top-item">
top
</div>
<div class="center-item">
center
</div>
</div>

<style>
body {
height: 50vh;
}
.top-item {
flex: 1 0 100%;
text-align: center;
align-self: flex-start;
}
.center-item {
align-self: center;
}
.flexbox-container {
display: -ms-flexbox;
display: -webkit-flex;
display: flex;

-ms-flex-align: center;
-webkit-align-items: center;
-webkit-box-align: center;

justify-content: center;
height: 100%;
flex-wrap: wrap;
}
</style>


My problem and thus question: how to precisely make the center div align at the center? Currently there is space above it <=> it aligns below the desired height

I have the feeling that this will be about correct usage of
align-content
in the parent container but I cannot seem to figure it out.

Answer Source

You can position the top-item as absolute and then add align-content: center to the flexbox container - see demo below:

  body {
    height: 50vh;
    background: blue;
  }
  .top-item {
    flex: 1 0 100%;
    text-align: center;
    align-self: flex-start;
    position: absolute; /* ADDED */
  }
  .center-item {
    align-self: center;
  }
  .flexbox-container {
    display: flex;
    background: green;
    justify-content: center;
    height: 100%;
    flex-wrap: wrap;
    align-content: center; /* ADDED */
    position: relative; /* ADDED */
  }
<div class="flexbox-container">
  <div class="top-item">
    top
  </div>
  <div class="center-item">
    center
  </div>
</div>