你可能想不到,只用「兩行 CSS」,就能讓你的卡片、圖片、內(nèi)容塊「自動適應(yīng)」各種屏幕寬度,徹底擺脫復(fù)雜的媒體查詢! 秘訣就是 CSS Grid 的 auto-fill 和 auto-fit。

馬上教你用!?
?? 基礎(chǔ)概念
假設(shè)你有這樣一個需求:
只需在父元素加兩行 CSS 就能實現(xiàn):
/* 父元素 */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
/* 子元素 */
.item {
height: 200px;
background-color: rgb(141, 141, 255);
border-radius: 10px;
}
下面詳細解釋這行代碼的意思:
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
這是 CSS Grid 布局里定義列寬的常用寫法,逐個拆解如下:
1. grid-template-columns
- 作用:定義「網(wǎng)格容器」里有多少列,以及每列的寬度。
2. repeat(auto-fit, ...)
repeat 是個「重復(fù)函數(shù)」,表示后面的模式會被重復(fù)多次。auto-fit 是一個特殊值,意思是:「自動根據(jù)容器寬度,能放下幾個就放幾個」,每列都用后面的規(guī)則。
3. minmax(200px, 1fr)
minmax 也是一個函數(shù),意思是:「每列最小 200px,最大可以占 1fr(剩余空間的平分)」- 當屏幕寬度很窄時,每列「最小寬度是 200px」,再窄就會換行。
- 當屏幕寬度變寬,卡片會自動拉伸,每列「最大可以占據(jù)剩余空間的等分」(
1fr),讓內(nèi)容填滿整行。
4. 綜合起來
- 網(wǎng)格會自動生成多列,每列最小 200px,最大可以平分一行的剩余空間。
- 屏幕寬了就多顯示幾列,屏幕窄了就少顯示幾列,自動換行,自適應(yīng)各種屏幕!
- 「不需要媒體查詢」,布局就能靈活響應(yīng)。
總結(jié)一句話:
?grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
讓你的網(wǎng)格卡片「最小 200px,最大自動填滿一行」,自動適應(yīng)任何屏幕,布局永遠美觀!
?
這里還能填 auto-fill,和 auto-fit 有啥區(qū)別?
?? auto-fill 和 auto-fit 有啥區(qū)別?
1. auto-fill
??? 「盡可能多地填充列,即使沒有內(nèi)容也會 “占位”」
?
- 會自動創(chuàng)建盡可能多的列軌道(包括空軌道),讓網(wǎng)格盡量填滿容器。
- 適合需要 “列對齊” 或“固定網(wǎng)格數(shù)”的場景。
2. auto-fit
??? 「自動適應(yīng)內(nèi)容,能合并多余空列,不占位」
?
- 會自動 “折疊” 沒有內(nèi)容的軌道,讓現(xiàn)有的內(nèi)容盡量拉伸占滿空間。
- 適合希望內(nèi)容自適應(yīng)填滿整行的場景。
?? 直觀對比
假設(shè)容器寬度能容納 10 個 200px 的卡片,但你只放了 5 個卡片:
auto-fill 會保留 10 列寬度,5 個卡片在前五列,后面五列是 “空軌道”。auto-fit 會折疊掉后面五列,讓這 5 個卡片拉伸填滿整行。

?? Demo 代碼:
<h2>auto-fill</h2>
<div class="grid-fill">
<div>item1</div>
<div>item2</div>
<div>item3</div>
<div>item4</div>
<div>item5</div>
</div>
<h2>auto-fit</h2>
<div class="grid-fit">
<div>item1</div>
<div>item2</div>
<div>item3</div>
<div>item4</div>
<div>item5</div>
</div>
.grid-fill {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 16px;
margin-bottom: 40px;
}
.grid-fit {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
}
.grid-fill div {
background: #08f700;
}
.grid-fit div {
background: #f7b500;
}
.grid-fill div,
.grid-fit div {
padding: 24px;
font-size: 18px;
border-radius: 8px;
text-align: center;
}
兼容性
caniuse.com/?search=aut…[1]

?? 什么時候用 auto-fill,什么時候用 auto-fit?
「希望每行 “有多少內(nèi)容就撐多寬”,用 auto-fit」
適合卡片式布局、相冊、響應(yīng)式按鈕等。
「希望 “固定列數(shù) / 有占位”,用 auto-fill」
比如表格、日歷,或者你希望網(wǎng)格始終對齊,即使內(nèi)容不滿。
?? 總結(jié)
?? 小結(jié)
auto-fill 更像 “占位”,auto-fit 更像 “自適應(yīng)”- 推薦大部分響應(yīng)式卡片用
auto-fit - 善用
minmax 配合,讓列寬自適應(yīng)得更自然
只需兩行代碼,你的頁面就能優(yōu)雅適配各種屏幕!
閱讀原文:原文鏈接
該文章在 2025/5/19 10:01:51 編輯過