限制垂直弹性框中儿童的宽度

时间:2016-08-02 19:13:46

标签: html css css3 flexbox

如何将子宽度限制为垂直弹性框中的内容?正如您在青色背景中看到的那样,子宽度占据了容器的宽度。我希望它只占用它所需的宽度。

.container{
  display: flex;
  background: yellow;
  flex-direction: column;
  padding: 5px;
}

.content{
  background: cyan;
  margin: 5px;
}
<div class="container">
  <div class="content">hello whats up</div>
  <div class="content">hello whats up</div>
</div>

1 个答案:

答案 0 :(得分:2)

弹性容器的初始设置为align-items: stretch

此设置会导致弹性项目扩展容器横轴的整个长度。 (此设置允许在flexbox中使用相等高度的列。)

当你在flex-direction: column时,横轴是水平的,儿童会默认扩展容器的全宽。

您可以使用容器上的align-items: flex-start覆盖默认值,或者在每个弹性项目上覆盖align-self: flex-start

&#13;
&#13;
.container{
  display: flex;
  background: yellow;
  flex-direction: column;
  padding: 5px;
}

.content{
  background: cyan;
  margin: 5px;
  align-self: flex-start; /* NEW */
  
}
&#13;
<div class="container">
  <div class="content">hello whats up</div>
  <div class="content">hello whats up</div>
</div>
&#13;
&#13;
&#13;

参考文献: