2

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 vertically centered. Setting align-items: center changes height of the parent div.

.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;
}
<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>

Comment out the align-items and it fits alright. How should I resolve this issue?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
John Strood
  • 1,859
  • 3
  • 26
  • 39

1 Answers1

5

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:

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701