p { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
对于固定行高的文本框,咱们能够使用纯 CSS 来截断,思路是使用 float
属性,让另外一个元素覆盖掉最后的地方
效果图以下
为了方便理解,添加了背景色区分每一块css
<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>
参考来源:chrome
http://dev.mobify.com/blog/multiline-ellipsis-in-pure-css/app
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不会出现这种问题)flex
解决方案是对 .fc
设置 width
(或 max-width
或 min-width
) 或 overflow
属性ui
加上flexbox
.fc { width: 50%; }
或者spa
.fc { overflow: hidden; }
以后可获得咱们想要的效果firefox
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.code
大概是 chrome、opera 以及 firefox 的默认宽度属性的问题。blog