如何在表格表头<th>中添加输入框且不增加列宽?
如何实现表头添加输入框且不增加列宽?
现有一个表头宽度可自适应内容的表格,代码如下:
初始代码
CSS
.my-table { border: 1px solid; border-spacing: 0; table-layout: fixed; border-collapse: separate; box-sizing: border-box; } .my-table thead th { border-bottom: 1px solid ; border-right: solid 1px; } .my-table tbody td { border-top: none; border-left: none; border-bottom: 1px dotted; border-right: 1px solid; }
HTML
<table class="my-table"> <thead> <tr> <th> <div> ID </div> </th> <th> <div> Name </div> </th> </tr> </thead> <tbody> <tr> <td>1245</td> <td>Michael Knight</td> </tr> <tr> <td>1247</td> <td>Devon Miles</td> </tr> </tbody> </table>
现在需要在表头下方添加文本输入框,但输入框不能增加表头的列宽,实现方法如下:
解决方案代码
调整后的CSS
.my-table { border: 1px solid; border-spacing: 0; table-layout: fixed; border-collapse: separate; box-sizing: border-box; } .my-table thead th { border-bottom: 1px solid ; border-right: solid 1px; /* 关键:限制表头内元素宽度,超出部分隐藏 */ overflow: hidden; } .my-table thead th input { /* 输入框宽度设为100%,继承表头单元格的宽度 */ width: 100%; box-sizing: border-box; /* 可选:去掉输入框默认样式,和表格风格统一 */ border: none; outline: none; } .my-table tbody td { border-top: none; border-left: none; border-bottom: 1px dotted; border-right: 1px solid; }
修改后的HTML
<table class="my-table"> <thead> <tr> <th> <div> ID </div> <div> <input type="text"> </div> </th> <th> <div> Name </div> <div> <input type="text"> </div> </th> </tr> </thead> <tbody> <tr> <td>1245</td> <td>Michael Knight</td> </tr> <tr> <td>1247</td> <td>Devon Miles</td> </tr> </tbody> </table>
实现原理
- 给表头单元格
th添加overflow: hidden,确保内部元素不会撑开单元格宽度; - 将输入框的宽度设为
100%,并设置box-sizing: border-box,让输入框完全适配表头单元格的现有宽度,不会超出或撑大列宽; - 可选的输入框样式调整,去掉默认边框和轮廓,让它和表格融合更自然。
内容的提问来源于stack exchange,提问作者wuarmin
相关产品推荐
相关产品推荐

