为何表格表头行高度可设置,但表格数据行高度无法调整?
表格数据行高度无法修改的解决办法
我试过所有能找到的办法,只有调整表头行高度能让行高看起来接近统一,但数据行的高度怎么改都没效果。
我的HTML代码:
<div class="fields"> <table> <tr> <th>Year</th> <th id="clickable" onclick="openPopup('f2')">Yield/Year</th> <th id="clickable" onclick="openPopup('f3')">Yield/Year*3</th> <th id="clickable" onclick="openPopup('f4')">Yield/Year*3*4</th> </tr> <tr> <td>1</td> <td>387.58</td> <td>1162.74</td> <td>4650.96</td> </tr> </table> </div>
我的CSS代码:
.fields table { width: auto; table-layout: fixed; border-collapse: collapse; white-space: nowrap; } .fields td { font-family: Arial, sans-serif; color: #213B54; font-size: 16px; border-right: 2px solid #213B54; border-bottom: 2px solid #213B54; text-align: center; overflow: hidden; text-overflow: ellipsis; } .fields th { font-family: Arial, sans-serif; font-size: 16px; border-right: 2px solid #213B54; border-bottom: 2px solid #213B54; padding-top: 5px; padding-bottom: 5px; padding-left: 2px; padding-right: 2px; text-align: center; background-color: #9bdcdf; color: #067A9F; overflow: hidden; text-overflow: ellipsis; width: 75px; height: 10px; }
问题原因
你给表头<th>设置了height:10px,但同时加了padding-top:5px和padding-bottom:5px,光上下内边距就占了10px,再加上文字本身的行高,实际表头高度会远大于设置的height值。而数据行<td>没有设置内边距和高度,浏览器会默认用文字行高计算行高,导致和表头行高不一致。另外表格里的height属性优先级低于内边距和内容高度,单独给表头设height没用,数据行也没同步样式。
解决方法
把表头和数据行的通用样式统一,确保两者的内边距、行高一致:
修改后的CSS:
.fields table { width: auto; table-layout: fixed; border-collapse: collapse; white-space: nowrap; } /* 统一表头和数据行的基础样式 */ .fields th, .fields td { font-family: Arial, sans-serif; font-size: 16px; border-right: 2px solid #213B54; border-bottom: 2px solid #213B54; padding: 5px 2px; /* 统一上下左右内边距 */ text-align: center; overflow: hidden; text-overflow: ellipsis; width: 75px; /* 统一列宽 */ line-height: 1; /* 控制文字行高,减少额外高度 */ } /* 表头专属样式 */ .fields th { background-color: #9bdcdf; color: #067A9F; } /* 数据行专属样式 */ .fields td { color: #213B54; }
这样修改后,表头和数据行会共享相同的内边距、列宽和行高,高度自然统一。如果需要调整行高,直接修改padding的值或者添加height属性即可,只要保持两者样式同步就行。
内容的提问来源于stack exchange,提问作者good_variable_name
相关产品推荐
相关产品推荐

