Libon

关于文本溢出隐藏疑难杂症

#CSS
开发中对 text-overflow: ellipsis; 的一些题及解决方法。

ToC

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

这生效,但也不生效,为什么?(为了方便阅读和理解,下面将使用 inline-style 的方式来设置样式)。

这只对块级元素和行内块有效:

<p style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
  Lorem ipsum, dolor sit amet consectetur adipisicing elit. Explicabo assumenda consectetur vel aperiam vitae in inventoreeligendi atque,dolore quas ducimus, odio ea, nostrum tempore quibusdam repellendus fugiat temporibus necessitatibus?
</p>

但如果多了一些嵌套层级则开始失效:

<div style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
    <p>
      123 Lorem ipsum, dolor sit amet consectetur adipisicing elit. Explicabo assumenda consectetur vel aperiam vitae in inventore
      eligendi atque,
      dolore quas ducimus, odio ea, nostrum tempore quibusdam repellendus fugiat temporibus necessitatibus?
    </p>
</div>

这时候就需要调整类名的位置,将 ellipsis 类移动到元素 <p> 上,同时 <div>元素的类名样式可以移除:

<div>
    <p style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
      123 Lorem ipsum, dolor sit amet consectetur adipisicing elit. Explicabo assumenda consectetur vel aperiam vitae in inventore
      eligendi atque,
      dolore quas ducimus, odio ea, nostrum tempore quibusdam repellendus fugiat temporibus necessitatibus?
    </p>
</div>

这样似乎可以了,可如果……再多一层怎么办?它又双失效了:

<div style="display:flex">
    <div>
      <p style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
        123 Lorem ipsum, dolor sit amet consectetur adipisicing elit. Explicabo assumenda consectetur vel aperiam vitae in inventore
        eligendi atque,
        dolore quas ducimus, odio ea, nostrum tempore quibusdam repellendus fugiat temporibus necessitatibus?
      </p>
  </div>
</div>

经过简单实验,如果最外层的元素的 display 属性不为 block 的话,这个例子中的属性设置依旧会失效,比如在项目中常用到的 flex``inlien-block``grid 属性等。这时候的解决办法也很简单:

<div style="display:flex">
    <div style="overflow:hidden">
      <p style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
        123 Lorem ipsum, dolor sit amet consectetur adipisicing elit. Explicabo assumenda consectetur vel aperiam vitae in inventore
        eligendi atque,
        dolore quas ducimus, odio ea, nostrum tempore quibusdam repellendus fugiat temporibus necessitatibus?
      </p>
  </div>
</div>

以上。


CD ..
回顾上一篇
JS 事件流