IE8下table th和td宽度样式混乱解决办法

来源:互联网 发布:周继红 田亮 知乎 编辑:程序博客网 时间:2024/06/05 20:00

先看看一个对比(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长单词的换行。

阅读全文
1 0