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

后端 未结 3 952
谎友^
谎友^ 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条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-14 05:40

    Question 1/2

    Yes! You can do it with flexbox:

    .box {
      /* Firefox */
      display: -moz-flex;
      -moz-justify-content: center;
      -moz-align-items: center;
    
      /* IE */
      display: -ms-flex;
      -ms-justify-content: center;
      -ms-align-items: center;
    
      /* Chrome | Safari */
      display: -webkit-flex;
      -webkit-justify-content: center;
      -webkit-align-items: center;
    
      /* Modern browsers */
      display: flex;
      justify-content: center;
      align-items: center;
    
      height: 40px;
      width: 150px;
      overflow: hidden;
      border: 1px solid black;
      margin-bottom: 40px;
      font-size: 16px;
      text-align: center;
    }
    
    .truncate {
      white-space: nowrap;
      overflow: hidden;
      -ms-text-overflow: ellipsis;  /* IE */
      -o-text-overflow: ellipsis;   /* Opera */
      text-overflow: ellipsis;      /* Other browsers */
    }

    one line of text

    two lines of text lorem ipsum

    thre lines of text lorem ipsum sin dolor whatever etc

    If you like to use Sass/SCSS and Compass your stylesheet will be like:

    @import 'compass';
    
    .box {
      @include flexbox((
        display: flex,
        justify-content: center,
        align-items: center 
      ), 1 2 3);
      height: 40px;
      width: 150px;
      overflow: hidden;
      border: 1px solid black;
      margin-bottom: 40px;
      font-size: 16px;
      text-align: center;
    }
    
    .truncate {
      @include ellipsis();
    }
    

    Question 3

    Javascript is required only if you want to truncate your text in multiple lines (on second/third line and so on..) So if it's a single line, CSS is the right way. Otherwise use Succinct

    Question 4

    You don't see text centered because your .box has display: flex property. Remove it and you will see it centered

提交回复
热议问题