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

如何在Vue+SCSS项目中实现指定的网格布局?

网格布局实现求助

我想要实现一种双列错落对齐的网格布局:左列项目整体向下偏移,同时保证左右两列的项目上下边缘能整齐对齐,不会出现右侧列下方项目错位的情况。

当前代码情况

Vue 模板代码

<div class="projects">
  <Project v-for="project in projects" :key="project.title" :title="project.title" :img="project.img" :link="project.link" />
</div>

项目组件 CSS

.project {
    overflow: hidden;
}

.img {
    width: 100%;
}
img {
    flex-grow: 1;
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
}    

已尝试的代码及问题

我试过用 Grid 布局,代码如下:

.projects {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 0.5rem;
  width: min(100%, 2000px);
  margin: 0 auto;
  padding: 0 1rem;
}

.project:nth-child(2n+1) {
  margin-top: 1rem;
}

但这样会导致右侧列的下方图片无法和上方图片整齐对齐,问题出在行的设置上。

解决方案

方案一:利用 Grid 原生跨行能力(推荐)

用 Grid 的grid-row属性实现偏移,避免 margin 破坏网格对齐规则:

.projects {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-auto-rows: minmax(180px, auto); /* 自适应行高,可根据项目调整 */
  grid-column-gap: 0.5rem;
  grid-row-gap: 1.5rem; /* 行间距包含偏移空间 */
  width: min(100%, 2000px);
  margin: 0 auto;
  padding: 0 1rem;
}

/* 左列项目跨两行,实现向下偏移效果 */
.project:nth-child(2n+1) {
  grid-row: span 2;
  align-self: start; /* 保持项目顶部对齐 */
}

方案二:正负 margin 抵消法(适合固定高度项目)

如果项目高度统一,可通过正负 margin 抵消错位:

.projects {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 0.5rem;
  width: min(100%, 2000px);
  margin: 0 auto;
  padding: 0 1rem;
}

.project:nth-child(2n+1) {
  margin-top: 1rem;
}
/* 右列项目添加负margin,抵消左列偏移带来的错位 */
.project:nth-child(2n) {
  margin-top: -1rem;
}

Vue 动态适配(针对高度不固定项目)

如果项目高度不一致,可在组件中监听图片加载,动态调整网格行高:

// Project 组件内
mounted() {
  const img = this.$el.querySelector('img');
  img.onload = () => {
    this.$emit('img-loaded', img.offsetHeight);
  };
}

// 父组件模板
<Project 
  v-for="(item, idx) in projects" 
  :key="item.title" 
  :title="item.title" 
  :img="item.img" 
  :link="item.link"
  @img-loaded="setRowHeight(idx, $event)"
/>

// 父组件方法
setRowHeight(index, height) {
  // 通过CSS变量动态设置对应行高
  document.documentElement.style.setProperty(`--row-${index}`, `${height + 20}px`);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 05:36:28