DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> 前端技巧
表格儲存格內容溢出時顯示省略號
編輯:前端技巧     

需求說明

前端開發中經常遇到這樣的情況:需要限制儲存格的寬度,內容超出時用省略號表示。做法並不複雜,關鍵是三個 CSS 屬性加上一個表格屬性。

三個關鍵屬性

1. 控制文字不換行

white-space: nowrap;

2. 超出隱藏並顯示省略號

overflow: hidden;
text-overflow: ellipsis;

3. 修改表格佈局演算法

table-layout: fixed;

table-layout 預設值是 auto,意思是欄寬由儲存格內容決定;改為 fixed 後,欄寬由表格寬度與欄寬設定決定。

這一步是許多人忽略的重點:只給表格設定欄寬其實沒有用,內容一多還是被撐開。要讓欄寬真正聽你的,必須加上 fixed。

注意兩點:表格必須設定寬度;如果只設表格寬度而不設欄寬,各欄會平均分配。

示範:未使用省略號

<table style="width:100%; table-layout:fixed;" border="1" cellspacing="0" cellpadding="0">
  <tr>
    <th style="width:10%">姓名</th>
    <th style="width:20%">年齡</th>
    <th style="width:30%">性別</th>
    <th style="width:40%">地址</th>
  </tr>
  <tr>
    <td>李四ssssssssssssssssssssssss</td>
    <td>13</td><td>男</td><td>山東</td>
  </tr>
</table>

這時四欄的寬度比例是 10%、20%、30%、40%,看起來正常。

但把姓名欄的內容加長之後,欄寬比例就被破壞了,畫面幾乎不能看。

加上省略號

只需為儲存格補上三行:

td {
    white-space: nowrap;    /* 控制單行顯示 */
    overflow: hidden;       /* 超出隱藏 */
    text-overflow: ellipsis;/* 以省略號表示被隱藏的內容 */
}

完整寫法:

<style>
table { width:100%; table-layout:fixed; }
.name { width:10%; } .age { width:20%; }
.sex  { width:30%; } .addr { width:40%; }
td {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
</style>

<table border="1" cellspacing="0" cellpadding="0">
  <thead>
    <tr>
      <th class="name">姓名</th>
      <th class="age">年齡</th>
      <th class="sex">性別</th>
      <th class="addr">地址</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>李四ssssssssssssssssssssssssssss</td>
      <td>13</td><td>男</td><td>山東</td>
    </tr>
  </tbody>
</table>

改完之後,超出的部分整齊地收在省略號後面,欄寬比例也不再被內容破壞。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved