Wrap a text within only two lines inside div

前端 未结 11 810

I want to wrap a text within only two lines inside div of specific width. If text goes beyond the length of two lines then I want to show elipses. Is there a way to do that

11条回答
  •  余生分开走
    2020-12-04 09:20

    Typically a one-line truncate is quite simple

    .truncate-text {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    

    Two line truncate is a little bit more tricky, but it can be done with css this example is in sass.

    @mixin multiLineEllipsis($lineHeight: 1.2rem, $lineCount: 2, $bgColor: white, $padding-right: 0.3125rem, $width: 1rem, $ellipsis-right: 0) {
      overflow: hidden; /* hide text if it is more than $lineCount lines  */
      position: relative; /* for set '...' in absolute position */
      line-height: $lineHeight; /* use this value to count block height */
      max-height: $lineHeight * $lineCount; /* max-height = line-height * lines max number */
      padding-right: $padding-right; /* place for '...' */
      white-space: normal; /* overwrite any white-space styles */
      word-break: break-all; /* will break each letter in word */
      text-overflow: ellipsis; /* show ellipsis if text is broken */
    
      &::before {
        content: '...'; /* create the '...'' points in the end */
        position: absolute;
        right: $ellipsis-right;
        bottom: 0;
      }
    
      &::after {
        content: ''; /* hide '...'' if we have text, which is less than or equal to max lines and add $bgColor */
        position: absolute;
        right: 0;
        width: $width;
        height: 1rem * $lineCount;
        margin-top: 0.2rem;
        background: $bgColor; /* because we are cutting off the diff we need to add the color back. */
      }
    }
    

提交回复
热议问题