一、单行文字
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>testOverFlow</title> <style type="text/css"> .container { margin-top: 10px; width: 200px; height: 44px; line-height: 44px; background-color: lightgray; } #singleTextDiv { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } #singleP { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } #singleSpan { display: block; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } </style> </head> <body> <div class="container"> <div id="singleTextDiv"> 少时诵诗书少时诵诗书少时诵诗书少时诵诗书少时诵诗书少时诵诗书 </div> </div> <div class="container"> <p id="singleP">少时诵诗书少时诵诗书少时诵诗书少时诵诗书少时诵诗书少时诵诗书</p> </div> <div class="container"> <span id="singleSpan">少时诵诗书少时诵诗书少时诵诗书少时诵诗书少时诵诗书少时诵诗书</span> </div> </body> </html>
|
div
和p
是块级元素,span
是内联元素,对块级元素设置text-overflow
、white-space
、overflow
三个属性标签即可
二、多行文字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>testOverFlow</title> <style type="text/css"> .container { margin-top: 10px; width: 200px; height: 44px; line-height: 44px; background-color: lightgray; } #doubleP { line-height: 22px; text-overflow: ellipsis; overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp:2; } #doubleSpan { display: block; line-height: 22px; text-overflow: ellipsis; overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp:2; } </style> </head> <body> <div class="container"> <p id="doubleP">少时诵诗书少时诵诗书少时诵诗书少时诵诗书少时诵诗书少时诵诗书</p> </div> <div class="container"> <span id="doubleSpan">少时诵诗书少时诵诗书少时诵诗书少时诵诗书少时诵诗书少时诵诗书</span> </div> </body> </html>
|
注意:
-webkit
代表Safari
、Chrome
等浏览器的私有属性
-webkit-line-clamp
用来限制要显示的行数,但是这是一个不规范的属性,必须组合其他的-webkit
属性才能达到效果