How can you use flexbox to vertically center text in a fixed-height div without overflowing above?

后端 未结 3 976
谎友^
谎友^ 2021-01-14 04:45

The first line of text in the third .box is raised above the top of the div and cut off. I would like it to appear the same as the second box (well actually ide

3条回答
  •  Happy的楠姐
    2021-01-14 05:43

    When align-self computes to center, the flex item is centered in the cross axis within the line.

    That's problematic if the flex item is bigger than the flex container, because it will overflow it both from above and below. And in case overflow is not visible, the upper part will be cut.

    To avoid this, you can center by using auto margins:

    .box {
      display: flex;
      height: 40px;
      width: 150px;
      overflow: auto;
      border: 1px solid black;
      margin-bottom: 20px;
      font-size: 16px;
      text-align: center;
    }
    .box > div {
      margin: auto;
    }
    one line of text
    two lines of text lorem ipsum
    thre lines of text lorem ipsum sin dolor whatever etc

    Note margin: auto needs to be added to each flex item. However, you can't select the anonymous flex item which wraps contiguous run of texts in the flex container. Therefore, I wrapped the text in div elements, which can be selected.

    If you don't want to alter the HTML, you can use pseudo-elements.

    .box {
      display: flex;
      flex-direction: column;
      height: 40px;
      width: 150px;
      overflow: auto;
      border: 1px solid black;
      margin-bottom: 40px;
      font-size: 16px;
      text-align: center;
    }
    .box::before, .box::after {
      content: '';
      margin-top: auto;
    }
    one line of text
    two lines of text lorem ipsum
    thre lines of text lorem ipsum sin dolor whatever etc

提交回复
热议问题