CSS Grid 布局 grid-template-columns 超出浏览器宽度解决方法
CSS HTML About 660 words现象
Grid的item默认min-width: auto,会让项目的最小宽度基于内容,导致换行/收缩受限。
在Grid中,1fr列的最小宽度会默认取min-content size(也受item的min-width:auto影响)。这意味着如果子项有不可换行的长内容或宽元素,列不会小于该内容的最小尺寸,进而导致容器被撑宽。
方法一
给网格项item统一min-width: 0
方法二
minmax(0, 1fr)的作用是:允许Grid列在需要时**真的收缩到0**,避免因为内容的最小宽度把整个Grid撑出水平滚动条。
<div
style={{
marginTop: '10px',
display: 'grid',
gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
gap: '10px',
}}
>
</div>
说明
grid-template-columns: 1fr 1fr 1fr;含义:共分三列,每列平分宽度。
实际上不是:
1fr不是最小0的弹性单位。- 在不小于内容最小宽度的前提下再分配剩余空间
当列里有:
- 很长不换行文本
- 图片 / 表格 / 代码块
white-space: nowrap
列会拒绝继续变窄,导致Grid容器就只能被撑宽,浏览器出现横向滚动条。
minmax(0, 1fr)等于明确告诉浏览器:
- 可以把这列压到
0 - 内容溢出由我负责(
wrap/ellipsis/hidden)
Views: 7 · Posted: 2026-04-17
———         Thanks for Reading         ———
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...