1. 程式人生 > >table-layout:fixed 應用

table-layout:fixed 應用

參考:http://www.zhangxinxu.com/wordpress/2014/04/%E8%87%AA%E9%80%82%E5%BA%94%E8%A1%A8%E6%A0%BC-%E5%AD%97%E7%AC%A6%E6%8D%A2%E8%A1%8C-%E6%BA%A2%E5%87%BA%E7%82%B9%E7%82%B9%E7%82%B9-table-text-overflow-ellipsis-word-wrap-break-all/

應用場景一:

當表格中有很長的英文時,如果沒有設定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+