如何让 CSS Grid 项目占用剩余空间?

新手上路,请多包涵

我有一张用 CSS 网格布局构建的卡片。左边可能有一个图像,右上角可能有一些文本,右下角可能有一个按钮或链接。

在下面的代码中,如何让绿色区域占用尽可能多的空间,同时让蓝色区域占用尽可能少的空间?

果岭应尽可能将蓝色区域向下推。

https://jsfiddle.net/9nxpvs5m/

 .grid {
  display: grid;
  grid-template-columns: 1fr 3fr;
  grid-template-areas:
    "one two"
    "one three"
}

.one {
  background: red;
  grid-area: one;
  padding: 50px 0;
}

.two {
  background: green;
  grid-area: two;
}

.three {
  background: blue;
  grid-area: three;
}
 <div class="grid">
  <div class="one">
    One
  </div>
  <div class="two">
    Two
  </div>
  <div class="three">
    Three
  </div>
</div>

原文由 Jens Törnell 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

grid-template-rows: 1fr min-content; 添加到您的 .grid 将得到您所追求的 :)。

 .grid {
  display: grid;
  grid-template-columns: 1fr 3fr;
  grid-template-rows: 1fr min-content;
  grid-template-areas:
    "one two"
    "one three"
}

.one {
  background: red;
  grid-area: one;
  padding: 50px 0;
}

.two {
  background: green;
  grid-area: two;
}

.three {
  background: blue;
  grid-area: three;
}
 <div class="grid">
  <div class="one">
    One
  </div>
  <div class="two">
    Two
  </div>
  <div class="three">
    Three
  </div>
</div>

Jens 编辑: 为了获得更好的浏览器支持,可以改用: grid-template-rows: 1fr auto; ,至少在这种情况下是这样。

原文由 Kevin Powell 发布,翻译遵循 CC BY-SA 3.0 许可协议

网格是一系列相交的行和列。

您希望第二列中的两个项目根据它们的内容高度自动调整它们的行高。

这不是网格的工作原理。对第二列中行高的这种更改也会影响第一列。

如果你必须使用 CSS Grid,那么我要做的是给容器,比方说,12 行,然后根据需要让项目跨行。

 .grid {
  display: grid;
  grid-template-columns: 1fr 3fr;
  grid-template-rows: repeat(12, 15px);
}

.one {
  grid-row: 1 / -1;
  background: red;
}

.two {
  grid-row: span 10;
  background: lightgreen;
}

.three {
  grid-row: span 2;
  background: aqua;
}

.grid > div {
  display: flex;
  align-items: center;
  justify-content: center;
}
 <div class="grid">
  <div class="one">One</div>
  <div class="two">Two</div>
  <div class="three">Three</div>
</div>

否则,您可以尝试 flexbox 解决方案。

 .grid {
  display: flex;
  flex-flow: column wrap;
  height: 200px;
}

.one {
  flex: 0 0 100%;
  width: 30%;
  background: red;
}

.two {
  flex: 1 0 1px;
  width: 70%;
  background: lightgreen;
}

.three {
  background: aqua;
}

.grid>div {
  display: flex;
  align-items: center;
  justify-content: center;
}
 <div class="grid">
  <div class="one">One</div>
  <div class="two">Two</div>
  <div class="three">Three</div>
</div>

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题