【问题标题】:How to use CSS to make the text display only one line and replace it with an ellipsis如何使用CSS使文本只显示一行并用省略号替换
【发布时间】:2022-01-06 05:55:55
【问题描述】:

目前我有个需求,需要显示一块文章最多一行,多余的部分需要用省略号代替……

网上一般推荐的方法如下:

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

但是由于我的布局,我不知道为什么要使用 white-space: nowrap;会造成布局混乱,所以我在找能满足这个要求的,但是我没有用white-space: nowrap;这个属性,其他 CSS 方法!

如果您有其他javascript方法可以做到,也欢迎您提供您宝贵的cmet,谢谢。

.text-line{
            height: 100px;
            background-color: #AAA8A8;
            display: inline-block;
            width: 300px;
            color: #000;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
<div class="text-line">loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlorem</div>

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    你可以用 CSS 来做,但它远不是最干净的:

    div {
      position: relative;
      display: block;
      overflow: hidden;
      
      width: 300px;
      
      --height: 1.2em;
      line-height: var(--height);
      height: var(--height);
    }
    
    div:after {
      bottom: 0;
      right: 0;
      position: absolute;
      content: "..."
    }
    <div>Lorem ipsum dolor sit amet, consectetur adipiscing 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.</div> 

    遗憾的是,任何更准确的内容都需要 JavaScript,如 text-overflow: ellipsis; requires white-space: nowrap。

    【讨论】:

      猜你喜欢
      • 2012-03-20
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      • 2016-05-22
      • 2020-12-10
      • 2017-09-06
      相关资源
      最近更新 更多