使flex容器宽度随其子项而增长

Ale*_*mov 6 html css css3 flexbox

这是简化的布局:

<div class="root">
  <div class="container">
    <div class="cell">
      <input type="text" class="contact"></input>
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是简化的CSS:

.root {
  background-color: red;
  overflow: auto;
  width: 300px;

}

.container {
  background-color: green;
  display: flex;
  height: 50px;
}

.cell {
  background-color: black;
  height: 30px;
}

.contact {
  width: 400px;
}
Run Code Online (Sandbox Code Playgroud)

这是jsFiddle.

我有点意外的是,它的container宽度与它的孩子所需的宽度不同,而是受到它的限制root div.您可以在此jsFiddle中看到红色区域(根div)未填充绿色container div.

有人可以解释为什么flex容器宽度不会随着它的孩子而增长以及如何解决这个问题?

LGS*_*Son 16

块元素增长到其父宽度,内联随其内容增长.

这里可以找到一个更好,更深入的解释:


改为inline-flex,你得到了预期的结果.

.root {
  background-color: red;
  overflow: auto;
  width: 300px;
  
}

.container {
  background-color: green;
  display: inline-flex;                /*  changed  */
  height: 50px;
}

.cell {
  background-color: black;
  height: 30px;
}

.contact {
  width: 400px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="root">
  <div class="container">
    <div class="cell">
      <input type="text" class="contact">
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)