html - 为什么百分比宽度大小的 flex box 元素不能正确增加具有未指定(即自动)宽度的包装表的宽度?

标签 html css flexbox

请看一下这个片段:

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>
(如果您想更轻松地使用它,这里有一个代码笔:http://codepen.io/anon/pen/MKJmBM)

请注意,左上角中的文字并不完全适合它。 (至少在 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/

相关文章:

php - 如果未加载,可替代 WebGL

javascript - IE6 中的出生日期选择器问题

html - 两个 div 动态填充视口(viewport)高度

html - 为什么 flex 元素不缩小过去的内容大小?

html - flex 盒子的问题

html - 我怎样才能让更广泛的 child 从他们绝对定位的 parent 中溢出?

JavaScript 仅适用于实际的表格页面

html - 奇怪的 float 错误

iphone - css 100% 宽度 iphone

javascript - Facebook like box load 事件 jquery