请看一下这个片段:
table {
background-color: yellow;
box-shadow: inset 0 0 1px red;
max-width: 100%;
/* You would get similarly strange behavior with collapsing borders: */
/* border-collapse: collapse; */
}
td {
background-color: lightgreen;
box-shadow: inset 0 0 1px blue;
max-width: 100%;
}
.flex {
max-width: 100%;
display: flex;
flex: 1;
background-color: lightblue;
box-shadow: inset 0 0 1px black;
flex-wrap: wrap;
}
.box {
width: 50%;
background-color: cyan;
border-radius: 9px;
box-shadow: inset 0 0 1px red;
}
<table>
<tr>
<td>
<div class="flex">
<div class="box">
123456789ABCDEFGHIJKL
</div>
<div class="box">
meeedium
</div>
<div class="box">
short
</div>
</div>
</td>
</tr>
</table>
请注意,左上角框
中的文字并不完全适合它。 (至少在 Chrome 中没有。)我假设包装表会尝试“推”它的宽度,以使其内容完全适合自身。那么这是一个实现错误吗?还是未指定的行为?还是我的代码存在缺陷?
有人可以解释这种行为并提供解决方案来解决它吗?
(顺便说一句......我在尝试针对这个问题的一些初始解决方案草图时遇到了这种奇怪的行为:Using CSS, how to create a two-column grid with equal-width columns that are "only as narrow as required"?)
编辑:两个“可视列”的宽度应该相等。因此,涉及 max-width: 50%;
for .box
的解决方案不是我要找的。我的问题实际上是关于表格的:为什么它不增加宽度以使其所有内容都适合自身?
该问题的解决方案应确保表格不会“太宽”:它的宽度应仅与需要的一样宽,以便内容恰好适合 - 但不能宽一个子像素。
最佳答案
实际上,虽然我不是 100% 确定您想要什么,但解决方案似乎接近我之前的评论。从 .flex
中删除 flex: 1
并将 .box
中的 width:50%
更改为 flex-基础:50%
.
哦,当你这样做的时候,在 123456789ABCDEF
中添加一个空格,这样它就可以真正换行....
table {
background-color: yellow;
box-shadow: inset 0 0 1px red;
max-width: 100%;
/* You would get similarly strange behavior with collapsing borders: */
/* border-collapse: collapse; */
}
td {
background-color: lightgreen;
box-shadow: inset 0 0 1px blue;
max-width: 100%;
}
.flex {
max-width: 100%;
display: flex;
/* flex: 1; REMOVE */
background-color: lightblue;
box-shadow: inset 0 0 1px black;
flex-wrap: wrap;
}
.box {
flex-basis: 50%; /* CHANGED from -> width: 50% */
background-color: cyan;
border-radius: 9px;
box-shadow: inset 0 0 1px red;
}
<table>
<tr>
<td>
<div class="flex">
<div class="box">
123456789 ABCDEFGHIJKL <!-- NOTICE THE SPACE!!!!-->
</div>
<div class="box">
meeedium
</div>
<div class="box">
short
</div>
</div>
</td>
</tr>
</table>
关于html - 为什么百分比宽度大小的 flex box 元素不能正确增加具有未指定(即自动)宽度的包装表的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34572022/