align-items: center distorts height of parent

后端 未结 1 978
青春惊慌失措
青春惊慌失措 2021-01-25 23:59

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 vert

相关标签:
1条回答
  • 2021-01-26 00:37

    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:

    • Why is there a vertical scroll bar if parent and child have the same height?
    0 讨论(0)
提交回复
热议问题