说明
在前端开发中,经常会遇到需要限制单元格宽度并且内容超出部分显示省略号的的情况。下面就简单的介绍下如何达到这种效果。
准备知识
1. 控制文本不换行
white-space: nowrap;
2. 超出长度时,出现省略号
overflow:hidden;text-overflow:ellipsis
3. 修改表格布局算法
table-layout:fixed;
table-layout的默认值为automatic,意思是列宽度由单元格内容设定。而fixed意思是列宽由表格宽度和列宽度设定。
也就是说当你给表格设定列宽时,实际情况是不起作用的,当单元格内容过多时,依然会把宽度撑开。如果需要让表格的列宽显示方式由自己给单元格定义的列宽决定,就必须使用fixed这个值。注意:1、表格必须设置宽度 2、如果只设置表格宽度,而不设置列宽度的话,列的宽度会平均分配。
代码演示
如下代码所示,表格中安排了姓名、年龄、性别以及地址四列,这几个列的长度分别为10%、20%、30%、40%。
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8" /> 5 <title>表格演示</title> 6 <style type="text/css"> 7 table{ 8 width: 100%; 9 table-layout: fixed;10 }11 .name{12 width: 10%;13 }14 .age{15 width: 20%;16 }17 .sex{18 width: 30%;19 }20 .addr{21 width: 40%;22 }23 24 </style>25 </head>26 <body>27 <table border="1" cellspacing="0" cellpadding="0">28 <thead>29 <tr>30 <th class="name">姓名</th>31 <th class="age">年龄</th>32 <th class="sex">性别</th>33 <th class="addr">地址</th>34 </tr>35 </thead>36 <tbody>37 <tr>38 <td>李四</td>39 <td>13</td>40 <td>男</td>41 <td>山东</td>42 </tr>43 <tr>44 <td>李四</td>45 <td>13</td>46 <td>男</td>47 <td>山东</td>48 </tr>49 <tr>50 <td>李四</td>51 <td>13</td>52 <td>男</td>53 <td>山东</td>54 </tr>55 </tbody>56 </table>57 </body>58 </html>
显示效果如下所示:
很容易可以看出,姓名、年龄、性别以及地址等列的长度分别是10%、20%、30%、40%。
如果将第一个的姓名内容增多,不忍直视(>﹏<)!
不忍直视(>﹏<)!!
如何把单行内容超出部分显示为省略号呢?话不多说,上代码!
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8" /> 5 <title>表格演示</title> 6 <style type="text/css"> 7 table{ 8 width: 100%; 9 table-layout: fixed;10 }11 .name{12 width: 10%;13 }14 .age{15 width: 20%;16 }17 .sex{18 width: 30%;19 }20 .addr{21 width: 40%;22 }23 td{24 white-space: nowrap;/*控制单行显示*/25 overflow: hidden;/*超出隐藏*/26 text-overflow: ellipsis;/*隐藏的字符用省略号表示*/27 }28 </style>29 </head>30 <body>31 <table border="1" cellspacing="0" cellpadding="0">32 <thead>33 <tr>34 <th class="name">姓名</th>35 <th class="age">年龄</th>36 <th class="sex">性别</th>37 <th class="addr">地址</th>38 </tr>39 </thead>40 <tbody>41 <tr>42 <td class="name2">李四sssssssssssssssssssssssssssssssssss</td>43 <td>13</td>44 <td>男</td>45 <td>山东</td>46 </tr>47 <tr>48 <td>李四</td>49 <td>13</td>50 <td>男</td>51 <td>山东</td>52 </tr>53 <tr>54 <td>李四</td>55 <td>13</td>56 <td>男</td>57 <td>山东</td>58 </tr>59 </tbody>60 </table>61 </body>62 </html>
修改后,效果如下:
原标题:表格单元格内容超出时显示省略号效果
关键词: