在Flexbox中时,CSS网格不会增长

2022-04-02 00:00:00 html css flexbox css-grid

我对css网格的理解是,它将增长以填充其父对象,但是当父对象的大小由FlexBox控制时,这似乎不能正常工作。

在this example中,我预计淡蓝色网格项会增长到覆盖红色区域。如果网格是独立的,这将正确工作,但一旦将其放置到Flex元素中(即使使用flex-grow: 1),它就完全不会增长;

这里发生了什么,有什么方法可以将样式调整为我预期的行为吗?


编码:

布局

<div class="normal-grid">
  <div class="grid-item">Thing 1</div>
  <div class="grid-item">Thing 2</div>
</div>
<div class="flex">
  <div class="flex-grid">
    <div class="grid-item">Thing 1</div>
    <div class="grid-item">Thing 2</div>
  </div>
</div>

样式

.normal-grid {
  height: 100px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr;
  background: red;
}

.flex {
  margin-top: 20px;
  height: 100px;
  display: flex;
  flex-direction: column;
}

.flex-grid {
  flex-grow: 1;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr;
  background: red;
}

.grid-item {
  background: lightblue;
}

解决方案

只需保持row方向(默认方向)即可获得拉伸效果:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
.normal-grid {
  height: 100px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr;
  background: red;
}

.flex {
  margin-top: 20px;
  height: 100px;
  display: flex;
  /*flex-direction: column;*/
}

.flex-grid {
  flex-grow: 1;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr;
  background: red;
}

.grid-item {
  background: lightblue;
}
<div class="normal-grid">
  <div class="grid-item">Thing 1</div>
  <div class="grid-item">Thing 2</div>
</div>
<div class="flex">
  <div class="flex-grid">
    <div class="grid-item">Thing 1</div>
    <div class="grid-item">Thing 2</div>
  </div>
</div>

相关文章