Text above vertically centered flex item

Viewed 36

I have two divs, one is a title and the other is the content

I want to have the second div with the content to be centered vertically and have the title above it.

If i do this the content gets pushed off center because the flexbox grows in both directions and thus the content div is not in the vertical center anymore.

I've tried using a grid with 3 rows instead but it isn't responsive enough and causes overflow, it did however, achieve what i wanted.

to illustrate what i want to achieve

The vertical center of the red div should be the vertical center of the parent div

1 Answers

You should place the green box inside of the the red box and position the green box on top of the red box with position: absolute;. With that approach the red box will stay in the center.

Example:

/* center the red box */

.some-parent-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

#red-box {
  position: relative;
  /* your styling */
}

#green-box {
  position: absolute;
  bottom: 100%;
  left: 0;
  right: 0;
  /** greenbox / title styling */
}
<div id="red-box">
  <div id="green-box" />
</div>

Related