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

如何让CSS网格在1行与2行时呈现不同布局?

解决网格布局根据行数调整垂直位置的问题

你的核心问题是固定的top:20%导致单行网格位置偏上,要实现根据行数动态调整布局,这里提供两种可行方案:

方案一:CSS容器查询(现代浏览器适用)

利用容器查询检测网格高度,自动切换布局逻辑。

首先修改布局结构,给网格套一个父容器,再通过容器查询控制样式:

/* 父容器:作为容器查询的载体,同时提供垂直居中的基础布局 */
.grid-wrapper {
  position: absolute;
  inset: 0; /* 占满整个视口 */
  display: flex;
  align-items: center;
  justify-content: center;
  container-type: size; /* 启用容器查询 */
}

/* 网格基础样式:单行时默认居中 */
.grid-con {
  display: grid;
  width: 1000px;
  grid-template-columns: 250px 250px 250px;
  padding: 5px 0;
  gap: 30px;
  color: #fff;
  overflow: hidden;
  justify-content: center;
  opacity: 1;
}

/* 当网格高度超过单行高度时(这里假设单行元素高度为250px,根据实际调整),应用原有top:20%布局 */
@container (height > calc(250px + 10px)) {
  .grid-con {
    position: absolute;
    top: 20%;
    right: 10%;
    margin: 0;
  }
}

方案二:JavaScript动态判断行数(兼容旧浏览器)

通过JS计算网格行数,给容器添加对应类来切换样式。

CSS部分

/* 基础样式:单行时垂直居中 */
.grid-con {
  position: absolute;
  display: grid;
  width: 1000px;
  grid-template-columns: 250px 250px 250px;
  padding: 5px 0;
  gap: 30px;
  color: #fff;
  overflow: hidden;
  justify-content: center;
  right: 10%;
  opacity: 1;
  top: 50%;
  transform: translateY(-50%);
}

/* 多行时应用原有top:20%布局 */
.grid-con.multi-row {
  top: 20%;
  transform: none;
}

JavaScript部分

const gridCon = document.querySelector('.grid-con');

function adjustGridLayout() {
  if (!gridCon) return;
  
  // 获取单个网格项的高度 + gap值
  const firstItem = gridCon.children[0];
  const rowHeight = firstItem.offsetHeight + parseInt(getComputedStyle(gridCon).gap);
  // 计算网格总行数
  const rowCount = Math.ceil(gridCon.offsetHeight / rowHeight);
  
  // 根据行数切换类
  rowCount > 1 ? gridCon.classList.add('multi-row') : gridCon.classList.remove('multi-row');
}

// 初始化执行
adjustGridLayout();

// 如果网格内容是动态加载的,在内容更新后重新执行,比如:
// 数据加载完成后调用 adjustGridLayout();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:07:07