With CSS, use “…” for overflowed block of multi-lines

后端 未结 16 2562
情话喂你
情话喂你 2020-11-22 07:15

with

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

\"...\" will be shown in the end of the line if overflowed. However, t

16条回答
  •  不要未来只要你来
    2020-11-22 07:40

    There are many answers here but I needed one that was:

    • CSS Only
    • Future-proof (gets more compatible with time)
    • Not going to break words apart (only breaks on spaces)

    The caveat is that it doesn't provide an ellipsis for the browsers that don't support the -webkit-line-clamp rule (currently IE, Edge, Firefox) but it does use a gradient to fade their text out.

    .clampMe {
      position: relative;
      height: 2.4em; 
      overflow: hidden;
    }
    
    .clampMe:after {
      content: "";
      text-align: right;
      position: absolute;
      bottom: 0;
      right: 0;
      width: 50%;
      height: 1.2em; /* Just use multiples of the line-height */
      background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 80%);
    }
    
    /* Now add in code for the browsers that support -webkit-line-clamp and overwrite the non-supportive stuff */
    @supports (-webkit-line-clamp: 2) {
      .clampMe {
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
      }
      
      .clampMe:after {
        display: none;
      }
    }

    There's a lot more text in here than what you'll ever see. Pellentesque habitant testalotish morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

    You can see it in action in this CodePen and you can also see a Javascript version here (no jQuery).

提交回复
热议问题