【问题标题】:How do I make the contents of a flex layout fill the parent?如何使 flex 布局的内容填充父级?
【发布时间】:2021-11-29 17:38:18
【问题描述】:

所以我正在尝试创建一个 flex 布局,其中子级填充父级的垂直空间。

我在这里尝试过:https://jsfiddle.net/3ryma0sn/50/

<body>
<div class="vLayout">
  <div class="hLayout">
    x
  </div>
  <div class="hLayout">
    x
  </div>
</div>
</body>

.vLayout {
  background-color: #ff0000;
  position: absolute;
  flex-wrap: nowrap;
  flex-direction: column;
  align-items: stretch;
  align-content: stretch;
  gap: 0px;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  margin: 10px;
  
}

.hLayout {
  background-color: #ffff00;
  margin: 10px;
  flex-grow: 1;
}

我的期望是因为父母是align-items: stretch 而孩子是flex-grow: 1,孩子应该伸展以填满父母。然而,子 div 只包装它们的内容:

我缺少什么来完成这项工作?

【问题讨论】:

  • 你添加了高度:100vh;给孩子?如果你有 2 你可以使用 height : 50vh;
  • 所以我刚试了一下,边距坏了。 IE。如果我想有边距,那么 50vh 会使黄色 div 溢出红色 div。有没有办法让它均匀地填充父母?
  • 你缺少 display:flex

标签: css reactjs flexbox


【解决方案1】:

您需要在 vLayout 类上显式设置显示属性,方法是添加:display: flex;

.vLayout {
  display: flex;
  background-color: #ff0000;
  position: absolute;
  flex-wrap: nowrap;
  flex-direction: column;
  align-items: stretch;
  align-content: stretch;
  gap: 0px;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  margin: 10px;
}

.vLayout>* {
  flex: 1 100%;
}

.hLayout {
  background-color: #ffff00;
  margin: 10px;
  flex-grow: 1;
}
<body>
  <div class="vLayout">
    <div class="hLayout">
      x
    </div>
    <div class="hLayout">
      x
    </div>
  </div>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 2021-06-21
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多