【问题标题】:How to stretch children to fill cross-axis?如何拉伸孩子填充横轴?
【发布时间】:2015-06-10 15:17:54
【问题描述】:

我有一个左右弹性框:

.wrapper {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  width: 100%;
  height: 70vh;
  min-height: 325px; 
  max-height:570px; 
}
<div class="wrapper">
  <div class="left">Left</div>
  <div class="right">Right</div>
</div>

问题是正确的孩子没有做出反应。具体来说,我希望它填充包装器的高度。

如何做到这一点?

【问题讨论】:

  • 它确实填满了包装器的高度!我在 Chrome 和 Firefox 中测试过,没有问题。也许您已经过多地简化了代码。您可以通过为孩子设置background-color 或在包装器中设置align-items: center 来测试它。
  • 是的,由于某些原因,safari 中没有填充包装器的高度...... chrome 和 firefox 通过在孩子中设置 height: '100%' 很好地做到了这一点

标签: css flexbox


【解决方案1】:
  • row-flexbox 容器的子容器会自动填充容器的垂直空间。

  • 如果您希望孩子填充剩余的水平空间,请为孩子指定 flex: 1;

.wrapper {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  width: 100%;
  height: 5em;
  background: #ccc;
}

.wrapper>.left {
  background: #fcc;
}

.wrapper>.right {
  background: #ccf;
  flex: 1;
}
<div class="wrapper">
  <div class="left">Left</div>
  <div class="right">Right</div>
</div>
  • 如果您希望两个孩子填充相同数量的水平空间,请为两个孩子指定 flex: 1;

.wrapper {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  width: 100%;
  height: 5em;
  background: #ccc;
}

.wrapper>div {
  flex: 1;
}

.wrapper>.left {
  background: #fcc;
}

.wrapper>.right {
  background: #ccf;
}
<div class="wrapper">
  <div class="left">Left</div>
  <div class="right">Right</div>
</div>

【讨论】:

  • flexflex-growflex-shrinkflex-basis 的简写属性。 flex: 1; 等价于flex-grow: 1;
  • 好像不需要align-items: stretch;
  • 如何添加间隙 10px。像素之间? =)
  • @fdrv,您可以在 flex 容器上使用 gap 属性。请注意,Safari 尚不支持它,但预计很快就会添加支持。或者,您可以在除第一个弹性项目之外的所有弹性项目上使用 margin-left
  • @BarryCap 感谢您的更正。事实上,flex: 1; 实际上等同于flex: 1 1 0;flex-grow: 1; flex-shrink: 1; flex-basis: 0;,根据docs for flex
猜你喜欢
  • 2013-04-17
  • 2017-06-10
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多