1. 程式人生 > >IE8下table th和td寬度樣式混亂解決辦法

IE8下table th和td寬度樣式混亂解決辦法

先看看一個對比(IE8下的table樣式)
這裡寫圖片描述
上面這種看似沒有問題,接下來看下一個:
這裡寫圖片描述
當table表格的 td內容很多並且換行 的時候,那麼在IE8下的table樣式就會混亂。此時無論給th還是td設定寬度都是 無效的!!!

言簡意賅,先給解決方案,再解釋:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<style type="text/css">
/* table */
.table{ background-color: #fff;border-collapse:collapse;border:1px solid #eee;width:100%;text-align: left;} .table td{border:1px solid #eee;padding:2px 5px;height: 26px; background:#ccc;color: #fff; } .table th{border:1px solid #eee;padding:2px 5px;height: 26px;background-color:#666;text-align:right;width
:120px
;font-weight: normal;word-break:break-all;color: #fff;font-size: 14px;}
@media \0screen\,screen\9 { .table-fixed-ie8{table-layout:fixed;}/*重點關注的地方!!!!!!!!! */ }
</style> <body> <table class="table table-fixed-ie8"> <col style="width: 100px;" /><!-- //重點關注的地方!!!!!!!!! -->
<col style="width: 25%;" /><!-- //重點關注的地方!!!!!!!!! --> <col style="width: 100px;" /><!-- //重點關注的地方!!!!!!!!! --> <col style="width: 25%;" /><!-- //重點關注的地方!!!!!!!!! --> <col style="width: 100px;" /><!-- //重點關注的地方!!!!!!!!! --> <col/><!-- //重點關注的地方!!!!!!!!! --> <tbody> <tr> <th>選項:</th> <td colspan="5">Jachin</td> </tr> <tr> <th>選項:</th> <td>Jachin</td> <th>選項:</th> <td>Jachin</td> <th>選項:</th> <td>Jachin</td> </tr> <tr> <th>選項:</th> <td>Jachin</td> <th>選項:</th> <td>Jachin</td> <th>選項:</th> <td>Jachin</td> </tr> <tr> <th>選項:</th> <td>Jachin</td> <th>選項:</th> <td colspan="3">Jachin</td> </tr> <tr> <th>123</th> <!-- 重點關注的地方!!!!!!!!! --><td colspan="5" style="word-wrap: break-word; word-break: break-all;">Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin,Jachin</td> </tr> </tbody> </table> </body> </html>

放效果圖(IE8下的th和td寬度隨意調動):
這裡寫圖片描述
這裡寫圖片描述
好了,這個就是完美解決IE8下table的th和td寬度不可控的方案了。
此時的th和td寬度隨意控制。

CSS屬性的:table-layout:fixed;固定表格佈局與自動錶格佈局相比,允許瀏覽器更快地對錶格進行佈局。在固定表格佈局中,水平佈局僅取決於表格寬度、列寬度、表格邊框寬度、單元格間距,而與單元格的內容無關。通過使用固定表格佈局,使用者代理在接收到第一行後就可以顯示錶格。(官方話)

其實設定了這個主要目的是可以在table元素裡面新增標籤,在對設定表格設定table-layer:fixed樣式後,發現表格中有 “一行合併過” ,其它沒有合併的行的“列寬會平均化”,對列寬的設定會失效。如果把表格的合併行去掉,又能正常顯示。
原因:table-layout: fixed 的表格,各列寬度由第一行決定,後面指定的寬度會被忽略。你第一行合併了,所以各列寬度均分了。

Tip:word-wrap: break-word; word-break: break-all;這兩個屬性在td內容很多的時候是需要設定的,否則樣式還是會亂。這兩個屬性用法可參考 CSS3 word-wrap和word-break長單詞的換行