css中table-layout:fixed的應用詳解

來源:互聯網
上載者:User
應用情境一:

當表格中有很長的英文時,如果沒有設定table-layout:fixed 或者 word-break:break-all,則儲存格顯示的寬度不是我們設定的寬度,如下:

<style>    table{border:2px solid #ccc;width: 100%;text-align: center;border-collapse:collapse;/*table-layout: fixed;*/}    td,th{height: 30px;border:2px solid #ccc;/*word-break: break-all;*/}</style><table width="400" border="1" id="table1">   <tr>       <td>3</td>      <td width="10%">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</td>      <td width="20%">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</td>   </tr>   <tr>       <td>3</td>       <td>4</td>       <td>5</td>   </tr></table>

上面代碼中給table元素添加 table-layout: fixed; 或者給td添加 word-break: break-all ,都可以達到表格安裝我們設定的寬度顯示:

table{border:2px solid #ccc;width: 100%;text-align: center;border-collapse:collapse;table-layout: fixed;}td,th{height: 30px;border:2px solid #ccc;/*word-break: break-all;*/}
table{border:2px solid #ccc;width: 100%;text-align: center;border-collapse:collapse;/*table-layout: fixed;*/}td,th{height: 30px;border:2px solid #ccc;word-break: break-all;}



應用情境二:

css的省略符號的一般寫法:

white-space: nowrap; overflow: hidden; text-overflow: ellipsis;

當你想在table中應用省略符號:

<style>
*{padding:0;margin:0;font-size: 12px;color: #333}
li{list-style: none;}

table{border:2px solid #ccc;width: 100%;text-align: center;border-collapse:collapse;}
td,th{height: 30px;border:2px solid #ccc;word-break: break-all;}

.ellipsis{white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}
</style>

<table width="400" border="1" id="table1">
<tr>
<td>3</td>
<td class="ellipsis" width="10%">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</td>
<td width="40%">5</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</table>

結果完全不是我們想要的:

解決方案:添加 table-layout: fixed;

<style>    *{padding:0;margin:0;font-size: 12px;color: #333}    li{list-style: none;}    table{border:2px solid #ccc;width: 100%;text-align: center;border-collapse:collapse;table-layout: fixed;}    td,th{height: 30px;border:2px solid #ccc;word-break: break-all;}    .ellipsis{white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}</style><table width="400" border="1" id="table1">        <tr>            <td>3</td>            <td class="ellipsis" width="10%">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</td>            <td width="40%">5</td>        </tr>        <tr>            <td>3</td>            <td>4</td>            <td>5</td>        </tr></table>

效果完全是我們想要的:


上面代碼均相容ie6+

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.