一、CSS超出顯示省略號
當文本長度超過所在容器的寬度時,CSS提供了文本溢出隱藏屬性來避免文本溢出容器。通過text-overflow屬性來設置文本顯示方式為省略號,具體有三個值:
<style>
.example1 {
width: 200px;
white-space: nowrap; /* 控制文本不換行 */
overflow: hidden;
text-overflow: ellipsis; /* 當文本溢出時,顯示為省略號 */
}
</style>
<p class="example1">This is a very long text. This is a very long text. This is a very long text.</p>
上面代碼中,當容器的寬度為200px時,如果文本長度超出該寬度,就會顯示為省略號。
二、CSS超出部分顯示省略號
如果要控制省略號的位置,可以通過max-lines屬性來控制文本的行數。先設置下面的代碼並注釋相應部分:
<style>
.example2 {
width: 200px;
white-space: nowrap;
overflow: hidden;
display: -webkit-box; /* 將對象作為彈性伸縮盒子模型顯示 */
-webkit-box-orient: vertical; /* 設置或檢索伸縮盒對象的子元素的排列方式 */
}
/* .example2::after {
content: "...";
} */
.example2.overflow {
-webkit-line-clamp: 2; /* 顯示幾行文本 */
}
</style>
接着在<p>標籤中添加.overflow類:
<p class="example2 overflow">This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text.</p>
上面的代碼中,設置了兩行文本顯示,當文本長度超過兩行時,就會顯示為省略號。如果想要省略號在文本後面顯示,只需要取消代碼注釋。
三、CSS超過三行展示省略號
如果要控制大於三行時才顯示省略號,需要設置-webkit-line-clamp屬性的值大於需要的行數。下面是相應的代碼:
<style>
.example3 {
width: 200px;
white-space: nowrap;
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
}
.example3::after {
content: "..."; /* 省略號 */
}
.example3.overflow {
-webkit-line-clamp: 4; /* 顯示幾行文本 */
}
</style>
在<p>標籤中添加.overflow類:
<p class="example3 overflow">This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text.</p>
四、CSS兩行省略號
如果只想讓兩行文本顯示省略號,可以使用max-height屬性來實現,max-height的值是<line-height> * 2,其中line-height是文本所在容器的行高。下面是相應的代碼:
<style>
.example4 {
width: 200px;
white-space: nowrap;
overflow: hidden;
max-height: 2.4em; /* 行高是1.2em,2行的高度就是2.4em */
text-overflow: ellipsis;
}
</style>
<p class="example4">This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text. This is a very long text.</p>
上面的代碼中,設置了2.4em的最大高度,同時採用了text-overflow屬性來實現省略號。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/300912.html