Grid布局下图片溢出问题排查与现有CSS代码修复咨询
解决方案
核心问题点
- 缺少全局样式重置,img默认行内块属性带来的底部留白会撑高容器,body默认边距会导致视口宽度计算溢出
- 移动端img设置
width: 100vw,若存在父容器边距会直接触发横向溢出 - 平板端Grid容器未限制宽度、单元格未做溢出处理,内容容易撑开预设的单元格尺寸
- 图片仅设置
max-height: 100%,未显式指定高度继承父单元格尺寸,高比例图片会直接溢出单元格
具体修改步骤
- 新增全局基础样式重置,清除默认边距与img默认异常行为
- 调整移动端img宽度规则,改为相对于父容器的100%宽度适配
- 给平板端Grid容器新增宽度限制、单元格溢出隐藏规则
- 统一平板端图片样式,显式指定宽高占满单元格,同时精简重复代码
完整调整后CSS代码
/* 新增全局基础重置 */ body { margin: 0; padding: 0; overflow-x: hidden; } img { display: block; max-width: 100%; height: auto; } /* mobile approach header*/ .container { background-color: black; display: flex; justify-content: center; flex-direction: column; align-content: center; align-items: center; height: 50vh; width: 100vw; } a { text-decoration: none; color: white; padding: 1rem; font-family: Arial, Helvetica, sans-serif; } @media screen and (max-width: 767px) { .main { display: grid; grid-template-rows: repeat(9, auto); } /* 改为100%宽度适配父容器,避免溢出 */ img { width: 100%; } } /* Tablet approach*/ @media screen and (min-width: 768px) { /* header*/ .container { flex-direction: row; justify-content: right; height: auto; } /*gallery*/ .tablet-main { display: grid; grid-template: repeat(5, 100vh) / 50fr 50fr; grid-template-areas: "image1 image2" "image3 image4" "image5 image6" "image7 image8" "image9 ."; /* 新增容器宽度与溢出限制 */ width: 100%; overflow: hidden; } /* 新增单元格溢出隐藏,避免内容撑开单元格 */ .tablet-main > * { overflow: hidden; } .pic { display: none; } /* 统一图片公共样式,精简重复代码 */ .bread, .candies, .charries, .eclair, .fruit, .milk, .orange { width: 100%; height: 100%; object-fit: cover; } /* 单独指定各图片的grid-area */ .bread { grid-area: image1; } .candies { grid-area: image2; } .charries { grid-area: image3; } .eclair { grid-area: image4; } .fruit { grid-area: image5; } .milk { grid-area: image6; } .orange { grid-area: image7; } }
内容的提问来源于stack exchange,提问作者Mudassar
相关产品推荐
相关产品推荐

