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

响应式CSS Grid在小浏览器窗口下未按预期切换为单列布局的问题

响应式CSS Grid在小浏览器窗口下未按预期切换为单列布局的问题

Hey there, let's break down why your responsive grid isn't behaving as expected—this is a super common gotcha with CSS Grid when mixing track spans and media queries!

The core issue here is that even though you're switching the grid to a single column (grid-template-columns: 1fr) in your narrow-screen media query, the original grid-column: span X rules on your child divs are still active.

Here's what's happening under the hood: When your grid switches to 1 column, a class like .content-grid-8 still has grid-column: span 8 applied. Browsers will try their best to honor that span value, which means they'll automatically add extra grid tracks to accommodate the 8-column span—even though you explicitly set grid-template-columns: 1fr. That's why you're still seeing elements sharing rows instead of stacking neatly.

The fix is straightforward: You need to reset those grid-column properties in your media query so every child element takes up the full width of the single column. Add this code inside your @media only screen and (max-width: 768px) block:

.content-grid-4,
.content-grid-6,
.content-grid-8,
.content-grid-12 {
  grid-column: span 1; /* You could also use `auto` here—both work */
}

This overrides the original span values for small screens, forcing each div to occupy 1 full column (which equals the entire width of the grid now). You can even test this quickly in DevTools: temporarily disable the grid-column rules on the child elements when the media query is active, and you'll see they stack immediately.

Since you've confirmed the media query is triggering correctly via DevTools, adding this reset will make your grid behave exactly like you expected—each div will sit on its own full-width row when the screen is narrow.

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 12:28:11