Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vertically center the contents of a flexbox item

I'm trying to center the CONTENTS of a flexbox item while using justify-content:stretch; It appears that the old trick of using display:table-cell;vertical-align:middle; doesn't work in this situation. What does?

.flex-container {
    display:flex;
    align-items:center;
    justify-content:stretch;
}
.flex-item {
    align-self:stretch;
}

<div class="flex-container">
    <div class="flex-item">I want to be vertically centered! But I'm not.</div>
</div>

BEFORE YOU ANSWER: There seems to be a lot confusion about what I'm asking. I'm trying to center the CONTENTS of the flex-item. With justify-content:stretch, the height of the item will stretch to the full height of the container, but the contents of the item floats to the top (at least in Chrome).

"A picture is worth a thousand words." (A) is what I've already got. (B) is what I want. enter image description here

like image 580
emersonthis Avatar asked Jan 31 '15 17:01

emersonthis


People also ask

How do I vertically center a div with Flex?

To center a div vertically and horizontally using flexbox, you need to wrap the div or div's inside a container with properties ' display: flex; flex-direction: column; justify-content: center;align-items: center; ', then just make the div ' text-align: center; ' if it has text.

How do I align content vertically centered?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.


Video Answer


1 Answers

It can be achieved by displaying each flex item as a flex container and then aligning the contents vertically by align-items property, as follows:

.flex-container {
  display:flex;
  align-items:center;
  height: 200px; /* for demo */
}

.flex-item {
  align-self:stretch;
  display:flex;
  align-items:center;
  background-color: gold; /* for demo */
}
<div class="flex-container">
    <div class="flex-item">
      I want to be vertically centered!
      <s>But I'm not.</s>
  </div>
</div>

As a side-note, if you omit the align-items:center; declaration of the .flex-container you can safely remove align-self:stretch; from flex items as well.

like image 60
Hashem Qolami Avatar answered Nov 08 '22 11:11

Hashem Qolami