
本文将介绍如何使用 CSS 控制表格列的宽度,实现当表格中新增列时,特定列能够自动收缩以适应可用空间。核心在于使用 max-width 属性限制列的最大宽度,并结合 text-overflow: ellipsis 属性在列内容超出时显示省略号,从而保证表格的整体布局不会超出容器。
关键在于对需要自动收缩的列(以下简称“可变列”)应用以下 CSS 属性:
以下是示例代码,演示了如何实现可变列的自动收缩:
HTML:
立即学习“前端免费学习笔记(深入)”;
<div id="tableContainer">
<table id="table">
<thead>
<tr id="headRow">
<td class="fixedCol">Column 1</td>
<td class="variCol">Variable Width Column: Use available</td>
</tr>
</thead>
<tbody id="body">
<tr id="row1">
<td class="fixedCol">Current Behavior</td>
<td class="variCol">table width expands beyond container </td>
</tr>
<tr id="row1">
<td class="fixedCol">Desired Behavior</td>
<td class="variCol">Width of this column to shrink to make room for new columns </td>
</tr>
</tbody>
</table>
</div>
<span id="myButton">Add Column</span>CSS:
.variCol {
position: relative;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 150px; /* 设置最大宽度 */
vertical-align: top;
background-color: yellow;
}
.fixedCol {
position: relative;
width: 150px;
}
table {
position: relative;
width: 700px;
max-width: 100%;
height: 200px;
border: 1px solid black;
}
#myButton {
background-color: lightgray;
cursor: pointer;
}
#tableContainer {
position: relative;
width: 700px;
height: 300px;
border: 1px solid black;
}JavaScript (用于动态添加列):
function AddColumn() {
const body = document.getElementById("body");
const head = document.getElementById("headRow")
const row1 = document.getElementById("row1");
let el = document.createElement("td");
const cols = head.childElementCount + 1;
el.className = "fixedCol";
head.append(el);
el.textContent = "Column " + cols;
el = document.createElement("td");
el.className = "fixedCol";
row1.append(el);
}
document.getElementById("myButton").addEventListener('click', AddColumn)代码解释:
通过使用 max-width 和 text-overflow: ellipsis 属性,可以轻松实现表格列的自动收缩功能,从而保证表格在各种情况下都能保持良好的布局和可读性。 结合动态添加列的 JavaScript 代码,可以创建更加灵活和动态的表格。
以上就是灵活控制表格列宽:CSS实现自动收缩的列的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号