0

As shown in this fiddle, I have a set of divs. I want them to stretch over the available vertical space and to keep their contents vertically centered. And I'm a great fan of flex, too. In the markup below, I get stuck.

<div class="outer">
  <div class="inner">Uno</div>
  <div class="inner">Duo</div>
</div>

Using the class below, the stretch is there but the text is at the top.

.beep { align-self: stretch; ... }

When I switch to this, the centering occurs as required but the stretch disappears.

.boop { align-self: center; ... }

How should I approach it to work as I want? I've tried playing around with the following styles both on the component itself and its parent.

.blopp{
  vertical-align: middle;
  align-items: stretch;
  align-content: stretch;
}

Finally, I got it working but using a horrible set of parent-child-grandparent-subchild atrocity as HTML markup. Even I can see that it's an ugly hack that will bite me in the donkey being obviously unstable.

As far I'm experienced with display flex, it's my understanding that things are easy or you do it wrong. Well, this was not easy...

Asons
  • 84,923
  • 12
  • 110
  • 165
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • You misunderstood. The `align-items` is used on flex parent, `align-self` on flex child. This is how the `rest` rule should look like: `div.rest { flex: 1; justify-content: flex-end; align-items: center; display: flex; } ` – Asons Apr 22 '19 at 09:13
  • you need to make the difference between the element and its content. Here you want to align the content and not the element (which make this a trivial use case of vertical alignment thus the duplicates) – Temani Afif Apr 22 '19 at 09:17
  • A note, I just saw that the `display: flex` were used in `inner` as well, and wouldn't be needed in the `rest` rule again. – Asons Apr 22 '19 at 09:21

1 Answers1

1

For you rest elements (which is also a flexbox), you should be using align-items: center for centering the text inside (you have used align-self: center which centers the rest as a flex item inside the outer flexbox).

See demo below:

div.outer {
  font-family: "Open Sans", Arial, Helvetica, sans-serif;
  display: flex;
  width: 100%;
  height: 101px;
  border: 3px solid pink;
}

div.inner {
  padding: 10px;
  background: lightgray;
  border: 1px solid darkgray;
  display: flex;
}

div.first {
  flex: 3;
}

div.rest {
  flex: 1;
  justify-content: flex-end;
  align-items: center; /* <-- note this */
}
<div class="outer">
  <div class="first inner">I'm the first</div>
  <div class="rest inner">we're</div>
  <div class="rest inner">the</div>
  <div class="rest inner">rest</div>
</div>
kukkuz
  • 41,512
  • 6
  • 59
  • 95