响应式Grid布局问题求助:桌面两列并排移动端堆叠
响应式两列布局问题解决方法
问题描述
我在实现两列布局时遇到问题,期望实现完全响应式效果:桌面端两列并排展示,移动端则变为上下堆叠。目前布局未达到预期,不确定问题出在grid-template-columns: repeat(auto-fit, minmax());还是display属性上。
原代码
HTML
<div class="container1"> <img src="img/image.jpg" class="picture1"> <div class="about"> <div class="col-sm-3half"> <div class="title"> <a class="arrow"></a> <a href="#" class="previousPages">ALL PRODUCTS / HAIRCARE</a> </div> </div> </div> </div>
CSS
.container1{ position: absolute; display: grid; grid-template-columns: 910px 516px; top: 0%; left: 14px; gap: 0rem; font-family: 'Lato'; } .picture1{ display: flex; width: 910px; height: 770px; } .about{ position: absolute; display: block; height: 770px; width: 516px; top: 0%; right: 0%; background: #F7F6F5; } .col-sm-3half{ width: 396px; margin-left: 45px; } .title{ display: flex; width: 360px; height: 61px; margin-bottom: 59px; margin-top: 23px; margin-left: 2px; /* 45px + 2px */ } .arrow{ display: flex; width: 14px; height: 9px; margin-top: 26px; margin-right: 10px; background: url(img/arrow.png); } .previousPages{ display: flex; width: 348px; height: 61px; left: 995px; top: 23px; font-style: normal; font-weight: 300; font-size: 12px; line-height: 159.1%; align-items: center; letter-spacing: 0.05em; text-decoration: none; color: #4D4D4D; }
问题分析
.container1使用固定宽度的grid-template-columns: 910px 516px,没有自适应能力,小屏幕下无法自动换行.about设置position: absolute,脱离Grid布局控制,导致Grid无法管理其位置- 图片和
.about都用固定宽高,移动端会超出视口,破坏布局
修改后的代码
CSS
.container1{ position: relative; display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 0; font-family: 'Lato'; width: 100%; left: 0; } .picture1{ width: 100%; height: auto; object-fit: cover; } .about{ position: static; height: auto; width: 100%; background: #F7F6F5; padding: 23px 45px; } .col-sm-3half{ width: 100%; margin-left: 0; } .title{ display: flex; width: 100%; height: auto; margin: 0 0 59px 0; align-items: center; } .arrow{ width: 14px; height: 9px; margin-right: 10px; background: url(img/arrow.png); background-size: contain; background-repeat: no-repeat; } .previousPages{ font-style: normal; font-weight: 300; font-size: 12px; line-height: 159.1%; letter-spacing: 0.05em; text-decoration: none; color: #4D4D4D; width: auto; height: auto; }
修改要点
- 将
.container1的position改为relative,grid-template-columns替换为repeat(auto-fit, minmax(320px, 1fr)),实现屏幕宽度自适应,小屏幕自动堆叠为单列 - 移除
.about的position: absolute,让它回到Grid布局中,由Grid管理位置 - 所有元素的固定宽高替换为百分比或
auto,确保不同屏幕下自适应 - 用
padding替代margin控制.about内边距,避免内容溢出 - 调整图片属性为
width:100%和height:auto,保持图片比例
内容的提问来源于stack exchange,提问作者gasparb
相关产品推荐
相关产品推荐

