在Flexbox中时CSS Grid不会增长

时间:2018-08-22 20:39:31

标签: html css flexbox css-grid

我对CSS Grid的理解是,它将增长以填充其父级,但是当父级的大小由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;
}

2 个答案:

答案 0 :(得分:1)

您可以将flex-basis: 100%;添加到.flex-grid以获得所需的行为。

.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;
  flex-basis: 100%;
}

.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>

当元素由flexbox控制时,必须考虑其初始尺寸。在这种情况下,.flex-grid似乎正在缩小-因此添加flex-basis: 100%会告诉浏览器其初始大小应为其大小的100%。

答案 1 :(得分:1)

只需保持row方向(默认方向),您将获得拉伸效果:

.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>