You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不使用grid-areas的情况下让3个Div与左侧图片并排?

实现Grid两栏布局:右侧多Div与左侧图片并排(不使用grid-areas)

我用Grid搭建了一个两栏布局,左侧放一张图片,希望右侧有3个Div并排显示在图片右侧,但目前只有1个Div能和图片对齐,另外2个Div跑到了图片下方。想知道不用grid-areas的话怎么解决这个问题?

现有代码

CSS

.wrapper {
  background-color: pink;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: auto auto 1fr;
}

.hero {
  background-color: red;
}

.foo {
  background-color: orange;
}

.bar {
  background-color: lime;
}

.baz {
  background-color: aqua;
}

img {
  width: 100%;
  display: block;
}

HTML

<div class="wrapper">
  <div class="hero">
    <img src="https://via.placeholder.com/1080x1080" alt="">
  </div>
  <div class="foo">
    foo
  </div>
  <div class="bar">
    bar
  </div>
  <div class="baz">
    baz
  </div>
</div>

解决方法

给左侧图片容器.hero添加grid-row: 1 / -1;属性,让它占据Grid容器的所有行:

.hero {
  background-color: red;
  grid-row: 1 / -1; /* 关键代码 */
}

原理说明

原来的Grid布局设置了3行,.hero默认只占据第一行第一列,导致右侧的.foo占第一行第二列,.bar和.baz分别占第二、三行第二列,但第一列的第二、三行是空的,视觉上就显得这两个Div在图片下方。

添加grid-row: 1 / -1;后,.hero会从第一行延伸到最后一行(-1代表最后一行),占据左侧列的全部高度,右侧的三个Div就会依次排列在第二列的三行中,实现和左侧图片并排的效果。

内容的提问来源于stack exchange,提问作者Emma Stone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:54:16