Skip to content Skip to sidebar Skip to footer

Align-items: Center Distorts Height Of Parent

I want to build, something like a carousel, that you can slide using a scrollbar. In each of the slides, there's a single line of text that should be both horizontally and vertical

Solution 1:

The problem is not align-items: center. That's all good.

The problem is that your flex container is an inline-level box (display: inline-flex), which activates the vertical-align: baseline default setting.

Since your middle item has two lines of text, the box adjusts its baseline to line-up with its siblings. (Notice how all boxes line up when they each have a single line of text.)

Just override the default with vertical-align: bottom.

.carousel .slide {
    vertical-align: bottom;
}

.carousel {
  width: 100%;
  background-color: #dbdbdb;
  overflow-y: visible;
  overflow-x: auto;
  white-space: nowrap;
}

.carousel .slide {
  display: inline-flex;
  width: 250px;
  height: 150px;
  margin: 10px 10px 10px 10px;
  background-color: #FFF;
  font-weight: bolder;
  font-size: 15px;
  white-space: pre-wrap;
  align-items: center;
  justify-content: center;
  text-align: center;
  text-align-last: center;
  vertical-align: bottom;  /* NEW */
}
<div class="carousel">
  <div class="slide">Lorem ipsum dolor</div>
  <div class="slide">quisquam est qui dolorem ipsum quia dolor sit amet lorem ipsum</div>
  <div class="slide">consectetur, adipisci</div>
</div>

Also note:

  • the problem doesn't exist when you remove align-items: center because the default value is stretch, which allows the text to align at the baseline (i.e., first line) across boxes regardless of the number of lines (demo)
  • flex-start would also work (demo)
  • flex-end would not (demo)

More details about vertical-align: baseline:


Post a Comment for "Align-items: Center Distorts Height Of Parent"