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