所以这就是我要说的:
var els = document.getElementsByClassName("stuff");
for (var i = 0; i < 20; ++i) {
for (var j = 0; j < 2; ++j) {
var el = document.createElement("div");
el.innerHTML = i;
els[j].appendChild(el);
}
}
.maintable {
width: 300px;
}
.maincell1,
.maincell2 {
background-color: red;
width: 50%;
height: 100px;
}
.maincell2 {
background-color: blue;
}
.stuff {
display: flex;
flex-wrap: nowrap;
background-color: green;
overflow: scroll;
}
.stuff div {
width: 30px;
height: 30px;
border: 1px solid black;
}
#fixtable {
width: 100%;
height: 100%;
table-layout: fixed;
}
<table class="maintable">
<tr>
<td class="maincell1">
<div class="stuff"></div>
</td>
<td class="maincell2"></td>
</tr>
</table>
<br>
<table class="maintable">
<tr>
<td class="maincell1">
<table id="fixtable">
<tr>
<td>
<div class="stuff"></div>
</td>
</tr>
</table>
</td>
<td class="maincell2"></td>
</tr>
</table>
如您在代码片段中所见,第一个 flex div 扩展了其所在单元格的 50% 宽度。我知道我可以固定主表格布局,但我希望另一列具有自动增长功能。
为了限制该特定单元格的自动增长,在第二个表格中,我在 flex div 周围包裹了另一个固定表格,它按照我需要的方式工作。
但我的问题是 - 有没有更优雅的方法来做到这一点?因为这很笨重......
最佳答案
除了嵌套表格,您可以将 flex 容器从流中取出:
.maincell1, .maincell2 {
position: relative;
}
.stuff.fix {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
这样单元格内的内容就不会影响它的宽度。
请注意,规范未定义自动表格布局,因此结果可能不完全可靠。重新考虑使用固定布局可能是个好主意。
var els = document.getElementsByClassName("stuff");
for (var i = 0; i < 20; ++i) {
for (var j = 0; j < 2; ++j) {
var el = document.createElement("div");
el.innerHTML = i;
els[j].appendChild(el);
}
}
.maintable {
width: 300px;
}
.maincell1,
.maincell2 {
background-color: red;
width: 50%;
height: 100px;
position: relative;
}
.maincell2 {
background-color: blue;
}
.stuff {
display: flex;
flex-wrap: nowrap;
overflow: scroll;
width: 100%;
}
.stuff div {
width: 30px;
height: 30px;
border: 1px solid black;
background-color: green;
}
.stuff.fix {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
align-items: center;
}
<table class="maintable">
<tr>
<td class="maincell1">
<div class="stuff"></div>
</td>
<td class="maincell2"></td>
</tr>
</table>
<br>
<table class="maintable">
<tr>
<td class="maincell1">
<div class="stuff fix"></div>
</td>
<td class="maincell2"></td>
</tr>
</table>
关于html - 防止表格单元格增加其宽度以包含宽内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32641032/