如何使Pentel展示页的Grid布局居中并消除底部滚动条
解决Grid布局左偏与底部滚动条问题
问题原因
- 底部滚动条:
pens-images-container同时设置了height:100vh和margin-top:2rem,总高度超出视口范围,导致垂直滚动条始终存在。 - Grid左偏及内容溢出:图片使用固定宽度
400px,未适配Grid列宽,当屏幕宽度较小时,图片会撑破容器,破坏Grid的居中效果。
修复后的代码
HTML(无需修改)
<div class="pens-images-container"> <div class="pens-images"> <img src="./images/black-energel-rtx-refillable-liquid-gel-pen.png" alt="black EnerGel RTX refillable liquid gel pen"> <img src="./images/blue-ballpoint-07-clear-barrel.png" alt="blue ballpoint 0.7 clear barell pen"> <img src="./images/EnerGel-X-retractable-gel-pen.png" alt="EnerGel-X retractable gel pen"> <img src="./images/tradio-fountaion-blue-ink-white-barrel-pen.png" alt="tradio fountain blue ink white barrel pen"> </div> </div>
修改后的CSS
* { box-sizing: border-box; padding: 0; margin: 0; } html, body { background-color: #f5f5dc; } .wrapper { margin-left: auto; margin-right: auto; width: 100%; } .pens-images-container { margin-top: 2rem; width: 100%; } .pens-images { margin: 0 auto; max-width: 70%; display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); grid-gap: 2em; padding: 0 1rem; } .pens-images img { width: 100%; aspect-ratio: 1/1; object-fit: contain; }
关键修改说明
- 移除
html, body的固定高度限制,让页面高度随内容自然调整。 - 将容器的
width:100vw改为width:100%,避免vw单位带来的横向溢出问题。 - 删除
pens-images-container的height:100vh,消除因margin叠加导致的垂直滚动条。 - 图片改为自适应宽度,通过
aspect-ratio:1/1保持正方形比例,object-fit:contain确保图片完整显示不变形。 - 给Grid容器添加左右内边距,优化小屏显示效果。
内容的提问来源于stack exchange,提问作者talopl
相关产品推荐
相关产品推荐

