如何实现 grid 布局顶部对齐?

各位好,我在用 grid 做一个页面的布局,请看代码

<div class="fruit-grid">
    <div class="fruit">hello1</div>
    <div class="fruit">hello2</div>
    <div class="fruit">hello3</div>
    <div class="fruit">hello4</div>
    <div class="fruit">hello5</div>
    <div class="fruit">hello6</div>
    <div class="fruit">hello7</div>
</div>

我想实现的是一共分三列,最左边的一列是 hello1 和 hello2;中间是 3,4,5;最右侧是 6 和 7。 css 部分代码如下

.fruit-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  align-items: start;
}

.fruit {
  width: 100%;
  margin-bottom: 10px;
}

/* 显示在最左 */
.fruit:nth-child(1),
.fruit:nth-child(2) {
  grid-column: 1;
}

/* 显示在中间 */
.fruit:nth-child(3),
.fruit:nth-child(4),
.fruit:nth-child(5) {
  grid-column: 2;
}

/* 显示在最右 */
.fruit:nth-child(6),
.fruit:nth-child(7) {
  grid-column: 3;
}

现在遇到的问题是,中间和右侧的内容不顶部对齐,我想要的显示形式是

1 3 6
2 4 7
5

但实际的效果是

1
2 3 
  4
  5 6
    7

请问这个该怎么解决,谢谢。

如上问题所说,想知道错在哪里了

阅读 981
avatarAI BotBETA

你的问题出在对齐项的理解上。你想要的布局是一个列从左到右排列,然后下一列从上到下排列,再下一列也是从上到下排列。但是,你当前的 CSS 代码将所有的列都设置为从上到下排列。

要解决这个问题,你需要将每一列的子元素设置为不同的对齐方式。在 CSS Grid 中,可以使用 align-itemsalign-self 属性来控制对齐。

以下是修改后的 CSS 代码:

.fruit-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.fruit {
  width: 100%;
  margin-bottom: 10px;
}

/* 显示在最左 */
.fruit:nth-child(1),
.fruit:nth-child(2) {
  grid-column: 1;
  align-self: start; /* 控制这两列的对齐方式 */
}

/* 显示在中间 */
.fruit:nth-child(3),
.fruit:nth-child(4),
.fruit:nth-child(5) {
  grid-column: 2;
  align-self: end; /* 控制这三列的对齐方式 */
}

/* 显示在最右 */
.fruit:nth-child(6),
.fruit:nth-child(7) {
  grid-column: 3;
  align-self: start; /* 控制这两列的对齐方式 */
}

这样,每一列的子元素都会根据你指定的对齐方式进行排列,从而实现了你想要的布局效果。

2 个回答

你这个描述前后有点矛盾啊

最左边的一列是 hello1 和 hello2;中间是 3,4,5;最右侧是 6 和 7
现在遇到的问题是,中间和右侧的内容不顶部对齐,我想要的显示形式是

1 3 6
2 4 7
5

不应该是

1 3 6
2 4 7
  5

.fruit-grid上添加grid-auto-flow: dense就可以了,它会使元素尽可能的使用前面空的网格,而不是产生新的。

  <div class="parent">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">\3</div>
    <div class="div4">4</div>
    <div class="div5">5</div>
    <div class="div6">6</div>
    <div class="div7">7</div>
  </div>
.parent {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  grid-column-gap: 0px;
  grid-row-gap: 0px;
}

.div1 {
  grid-area: 1 / 1 / 2 / 2;
}
.div2 {
  grid-area: 2 / 1 / 3 / 2;
}
.div3 {
  grid-area: 1 / 2 / 2 / 3;
}
.div4 {
  grid-area: 2 / 2 / 3 / 3;
}
.div5 {
  grid-area: 3 / 1 / 4 / 2;
}
.div6 {
  grid-area: 1 / 3 / 2 / 4;
}
.div7 {
  grid-area: 2 / 3 / 3 / 4;
}

image.png

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