Insert ellipsis (…) into HTML tag if content too wide

后端 未结 24 3003
名媛妹妹
名媛妹妹 2020-11-22 10:07

I have a webpage with an elastic layout that changes its width if the browser window is resized.

In this layout there are headlines (h2) that will have

24条回答
  •  [愿得一人]
    2020-11-22 11:07

    There's a solution for multi-line text with pure css. It's called line-clamp, but it only works in webkit browsers. There is however a way to mimic this in all modern browsers (everything more recent than IE8.) Also, it will only work on solid backgrounds because you need a background-image to hide the last words of the last line. Here's how it goes:

    Given this html:

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    Here's the CSS:

    p {
        position:relative;
        line-height:1.4em;
        height:4.2em;      /* 3 times the line-height to show 3 lines */
    }
    p::after {
        content:"...";
        font-weight:bold;
        position:absolute;
        bottom:0;
        right:0;
        padding:0 20px 1px 45px;
        background:url(ellipsis_bg.png) repeat-y;
    }
    

    ellipsis_bg.png being an image of the same color of your background, that would be about 100px wide and have the same height as your line-height.

    It's not very pretty, as your text may be cut of in the middle of a letter, but it may be useful in some cases.

    Reference: http://www.css-101.org/articles/line-clamp/line-clamp_for_non_webkit-based_browsers.php

提交回复
热议问题