如何修改CSS Grid容器的响应式布局行为满足自定义断点要求
响应式Grid布局调整方案
修改思路
你当前Grid自动折行的原因是auto-fit会根据容器宽度自动计算列数,要实现你要的断点规则,只需要新增两个指定列数的媒体查询,覆盖自动适配逻辑即可:
- 屏幕宽度≥939px时:强制Grid为4列布局,保证所有盒子始终在同一行
- 屏幕宽度≤938px时:强制Grid为2列布局,每行2个盒子
需要修改/新增的CSS代码
你只需要替换原来的.content样式,并且新增对应断点的规则即可:
/* 替换原有的.content样式 */ .content { display: grid; justify-content: center; gap: 20px; } /* 新增939px及以上宽度规则 */ @media screen and (min-width: 939px) { .content { grid-template-columns: repeat(4, minmax(200px, 230px)); /* 限制最大宽度避免盒子被拉得太宽 */ max-width: 980px; margin: 0 auto; } } /* 新增938px及以下宽度规则 */ @media screen and (max-width: 938px) { .content { grid-template-columns: repeat(2, minmax(200px, 230px)); max-width: 480px; margin: 0 auto; } }
原有的≤626px、≤405px的断点规则无需修改,会自动覆盖上面的规则实现小屏适配。
修改后完整CSS代码
@import url('https://fonts.googleapis.com/css2?family=Montserrat&display=swap'); * { box-sizing: border-box; margin: 0; padding: 0; } :root { --nav-clr:#ebebeb; --box-r: #f94144; --box-g: #43AA8B; --box-y: #F9C74F; --box-b: #577590; } body, html { height: 100vh; font-family: 'Montserrat', sans-serif; } /* nav bar */ nav { display: flex; height: 60px; background-color: var(--nav-clr); align-items: center; } .logo { width: 150px; height: auto; margin-left: 1em; } /* buttons */ .box-btn { width: auto; height: 259px; background: #43AA8B; border-radius: 30px; position: relative; } .box-btn::after { content: ''; position: absolute; display: inline-block; width: 100%; right: 0; bottom: 0; height: 100px; border-bottom-right-radius: 30px; border-bottom-left-radius: 30px; background: var(--nav-clr); z-index: 1; } .box-red { background-color: var(--box-r); } .box-green { background-color: var(--box-g); } .box-yellow { background-color: var(--box-y); } .box-blue { background-color: var(--box-b); } .content { display: grid; justify-content: center; gap: 20px; } /* 939px及以上宽度规则 */ @media screen and (min-width: 939px) { .content { grid-template-columns: repeat(4, minmax(200px, 230px)); max-width: 980px; margin: 0 auto; } } /* 938px及以下宽度规则 */ @media screen and (max-width: 938px) { .content { grid-template-columns: repeat(2, minmax(200px, 230px)); max-width: 480px; margin: 0 auto; } } /* main */ .main-wrapper { height: 100vh; display: grid; justify-content: center; grid-template-columns: 80vw; grid-template-rows: 25% 5% 65%; } /* header */ .title-wrapper { margin: 50px; display: inline-block; font-size: 1.3em; text-align: center; grid-row: 1/3; } /* SMALLER SCREENS */ @media screen and (max-width:700px) { .title-wrapper { font-size: 1em; margin: auto; } nav { justify-content: center; } } @media screen and (max-width:626px) { .content { grid-template-columns: repeat(auto-fit, 350px); } .box-btn { height: 350px; } .box-btn::after { width: 100%; height: 135px; } } @media screen and (max-width:405px) { .title-wrapper { font-size: .8em; } .main-wrapper { height: 100vh; } }
内容的提问来源于stack exchange,提问作者gmod boi
相关产品推荐
相关产品推荐

