单行文本截断
p {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
多行文本截断
对于固定行高的文本框,我们可以使用纯 CSS 来截断,思路是使用 float
属性,让另一个元素覆盖掉最后的地方
效果图如下
为了方便理解,添加了背景色区分每一块
<div class="container">
<div class="content">
Responsive layouts in material design adapt to any possible screen size. This UI guidance includes a flexible
grid that ensures consistency across layouts, breakpoint details about how content reflows on different screens,
and a description of how an app can scale from small to extra-large screens.
</div>
</div>
<style>
.container {
height: 200px;
width: 200px;
background-color: beige;
overflow: hidden;
}
.container::before {
content: "";
height: 100%;
width: 1em;
float: left;
background-color: #adcfea;
}
.container::after {
content: "...";
text-align: right;
background-color: lightblue;
height: 1em;
width: 2em;
margin-left: -1em;
float: right;
position: relative;
top: -1em;
left: calc(100% - 1em);
}
.content {
width: 100%;
margin-left: -1em;
float: right;
}
</style>
参考来源:
在 flexbox
中截断文本的问题
<div style="display:flex;">
<div class="fc">
<p>blablablablablablablablabla...blablablablablablablabla</p>
</div>
<div class="fc">
<p>blablablablablablablablabla...blablablablablablablabla</p>
</div>
</div>
<style>
p {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
我们期望的效果是两个文本在同一行各占百分之五十,溢出的文本被 ...
截断,但实际的效果是两段文字都在同一排完整的显示出来了。(Safari不会出现这种问题)
解决方案是对 .fc
设置 width
(或 max-width
或 min-width
) 或 overflow
属性
加上
.fc {
width: 50%;
}
或者
.fc {
overflow: hidden;
}
之后可得到我们想要的效果
原因
According to a draft spec, the above text should not fully collapse when the flex container is resized down. Because .subtitle has a width of 100%, the min-width: auto calculation that flexbox makes says that its container should be larger than we want.
大概是 chrome、opera 以及 firefox 的默认宽度属性的问题。
参考 :
Flexbox and Truncated Text