CSS ellipsis 與 padding 結合時的問題

  • 2019 年 10 月 15 日
  • 筆記

CSS 實現的文本截斷

考察如下代碼實現文本超出自動截斷的樣式代碼:

.truncate-text-4 {    overflow: hidden;    text-overflow: ellipsis;    display: -webkit-box;    -webkit-box-orient: vertical;    -webkit-line-clamp: 4;  }

使用如下的 HTML 片段進行測試:

<style>    .my-div {      width: 300px;      margin: 10px auto;      background: #ddd;    }  </style>  <div class="my-div truncate-text-4">    How Not To Shuffle - The Knuth Fisher-Yates Algorithm. Written by Mike James.    Thursday, 16 February 2017. Sometimes simple algorithms are just wrong. In    this case shuffling an .... In other words as the array is scanned the element    under  </div>

運行效果:

通過 CSS ellipsis 實現的文本截斷效果

通過 CSS ellipsis 實現的文本截斷效果

padding 的問題

一切都很完美,直到給文本容器加上 padding 樣式後。

  .my-div {      width: 300px;      margin: 10px auto;      background: #ddd;  +    padding: 30px;    }

現在的效果是這樣的:

padding 破壞了文本截斷

padding 破壞了文本截斷

因為 padding 佔了元素內部空間,但這部分區域卻是在元素內部的,所以不會受 overflow: hidden 影響。

解決辦法

line-height

當設置的 line-height 適當時,或足夠大時,可以將 padding 的部分抵消掉以實現將多餘部分擠出可見範圍的目標。

.my-div {    width: 300px;    margin: 10px auto;    background: #ddd;    padding: 30px;  +  line-height: 75px;  }

通過 line-height 修復

通過 line-height 修復

這種方式並不適用所有場景,因為不是所有地方都需要那麼大的行高。

替換掉 padding

padding 無非是要給元素的內容與邊框間添加間隔,或是與別的元素間添加間隔。這裡可以考慮其實方式來替換。

比如 margin。但如果元素有背景,比如本例中,那 margin 的試就不適用了,因為元素 margin 部分是不帶背景的。

還可用 border 代替。

.my-div {    width: 300px;    margin: 10px auto;    background: #ddd;  -  padding: 30px;  +  border: 30px solid transparent;  }

使用 border 替換 padding

使用 border 替換 padding

毫不意外,它仍然有它的局限性。就是在元素本身有自己的 border 樣式要求的時候,就會衝突了。

將邊距與內容容器分開

比較普適的方法可能就是它了,即將內容與邊距分開到兩個元素上,一個元素專門用來實現邊距,一個元素用來實現文本的截斷。這個好理解,直接看代碼:

<div className="my-div">    <div className="truncate-text-4">      How Not To Shuffle - The Knuth Fisher-Yates Algorithm. Written by Mike      James. Thursday, 16 February 2017. Sometimes simple algorithms are just      wrong. In this case shuffling an .... In other words as the array is scanned      the element under    </div>  </div>

而我們的樣式可以保持不動。

將邊距與內容容器分開

將邊距與內容容器分開

相關資源