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

如何在小屏幕下实现CSS Grid响应式杂志风格布局?

解决方案:使用CSS媒体查询实现小屏幕响应式Grid布局

要实现你需要的小屏幕布局,核心是通过**媒体查询(Media Query)**针对小屏幕设备重新定义Grid的列结构和子元素的网格区域。以下是修改后的完整代码:

修改后的CSS代码

.parent {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(2, 1fr);
  grid-gap: 10px;
}

.div {
  background: teal;
  padding: 12px;
}

/* 桌面端布局(保留原有设置) */
.div:nth-child(1) { grid-area: 1 / 1 / 2 / 3; }
.div:nth-child(2) { grid-area: 1 / 3 / 2 / 4; }
.div:nth-child(3) { grid-area: 1 / 4 / 2 / 5; }
.div:nth-child(4) { grid-area: 2 / 1 / 3 / 2; }
.div:nth-child(5) { grid-area: 2 / 2 / 3 / 4; }
.div:nth-child(6) { grid-area: 2 / 4 / 3 / 5; }

/* 小屏幕响应式布局(以768px为断点,可按需调整) */
@media (max-width: 768px) {
  .parent {
    grid-template-columns: repeat(2, 1fr); /* 小屏幕设为2列布局 */
    grid-template-rows: repeat(4, auto); /* 行高随内容自动适应 */
  }

  .div:nth-child(1) { grid-area: 1 / 1 / 2 / 3; } /* 跨2列,占满整行 */
  .div:nth-child(2) { grid-area: 2 / 1 / 3 / 2; } /* 第2行第1列 */
  .div:nth-child(3) { grid-area: 2 / 2 / 3 / 3; } /* 第2行第2列 */
  .div:nth-child(4) { grid-area: 3 / 1 / 4 / 3; } /* 跨2列,占满整行 */
  .div:nth-child(5) { grid-area: 4 / 1 / 5 / 2; } /* 第4行第1列 */
  .div:nth-child(6) { grid-area: 4 / 2 / 5 / 3; } /* 第4行第2列 */
}

代码说明

  1. 断点设置:这里用max-width: 768px作为小屏幕的判断阈值,你可以根据实际需求调整(比如改为600px)。
  2. 列结构调整:小屏幕下Grid设为2列,这样单个子元素占1列时就是50%宽度,占2列时自动铺满100%宽度。
  3. 网格区域重定义:通过grid-area重新指定每个div的位置,完全匹配你需要的小屏幕布局规则。
  4. 行高优化:将固定行高改为auto,避免内容溢出或空间浪费。

HTML代码(无需修改)

<div class="parent">
  <div class="div">1</div>
  <div class="div">2</div>
  <div class="div">3</div>
  <div class="div">4</div>
  <div class="div">5</div>
  <div class="div">6</div>
</div>

内容的提问来源于stack exchange,提问作者Md. Ibrahim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:47:45