这就是我要说的:
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>
正如您在代码片段中看到的,第一个伸缩div扩展了其所在单元格的50%宽度。我知道我可以只是使主表布局固定,但我想为另一列的自动增长功能。
为了限制该特定单元格中的自动增长,在第二个表中,我在flexdiv周围包装了另一个固定表,它的工作方式正是我需要的。
我的问题是——是否有更优雅的方式来做到这一点?
代替嵌套表,您可以将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>