單行文字溢出省略:
給容器添加css樣式:
.text-ellipsis{ overflow:hidden; text-overflow: ellipsis; white-space: nowrap; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width:200px; background-color: lightblue; margin:0 auto; } .text-ellipsis{ overflow:hidden; text-overflow: ellipsis; white-space: nowrap; } </style> </head> <body> <div class="text-ellipsis"> 歐派整體櫥櫃定制簡約現代 歐派整體櫥櫃定制簡約現代歐派整體櫥櫃定制簡約現代歐派整體櫥櫃定制簡約現代 </div> </body> </html>
如果容器使用了flex布局:
此時單行文字省略會出問題
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width:200px; background-color: lightblue; margin:0 auto; display: flex; justify-content: center; align-items: center; } .text-ellipsis{ overflow:hidden; text-overflow: ellipsis; white-space: nowrap; } </style> </head> <body> <div class="text-ellipsis"> 歐派整體櫥櫃定制簡約現代 歐派整體櫥櫃定制簡約現代歐派整體櫥櫃定制簡約現代歐派整體櫥櫃定制簡約現代 </div> </body> </html>
解決方法:不能直接一起使用,可以加個span包裹住文字,在span標簽上設置文字溢出隱藏
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width:200px; background-color: lightblue; margin:0 auto; display: flex; justify-content: center; align-items: center; } .text-ellipsis{ overflow:hidden; text-overflow: ellipsis; white-space: nowrap; } </style> </head> <body> <div> <span class="text-ellipsis">歐派整體櫥櫃定制簡約現代 歐派整體櫥櫃定制簡約現代歐派整體櫥櫃定制簡約現代歐派整體櫥櫃定制簡約現代</span> </div> </body> </html>
多行文字溢出省略:
這個也是可以實現的,但是兼容性不太好,只兼容webkit內核的
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width:180px; background-color: lightblue; margin:0 auto; } .multiline-ellipsis{ overflow:hidden; text-overflow: ellipsis; display:-webkit-box;/*流布局*/ -webkit-line-clamp: 3;/*3行*/ -webkit-box-orient: vertical;/*從頂部向底部垂直布置子元素*/ white-space: normal !important; word-wrap:break-word;/*允許長單詞換行到下一行*/ } </style> </head> <body> <div> <span class="multiline-ellipsis">歐派整體櫥櫃定制簡約現代 歐派整體櫥櫃定制簡約現代歐派整體櫥櫃定制簡約現代歐派整體櫥櫃定制簡約現代</span> </div> </body> </html>
注意這里有個坑,那就是父元素高度最好自適應,高度過小或者過大都會崩
高度過小無法顯示完整行數:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width:180px; background-color: lightblue; margin:0 auto; height:50px; } .multiline-ellipsis{ overflow:hidden; text-overflow: ellipsis; display:-webkit-box;/*流布局*/ -webkit-line-clamp: 3;/*3行*/ -webkit-box-orient: vertical;/*從頂部向底部垂直布置子元素*/ white-space: normal !important; word-wrap:break-word;/*允許長單詞換行到下一行*/ } </style> </head> <body> <div class="multiline-ellipsis"> 歐派整體櫥櫃定制簡約現代 歐派整體櫥櫃定制簡約現代歐派整體櫥櫃定制簡約現代歐派整體櫥櫃定制簡約現代 </div> </body> </html>
高度過大,在省略號之后還會繼續顯示……