Theme NexT works best with JavaScript enabled

ShunNien's Blog

不積跬步,無以致千里;不積小流,無以成江海。

0%

CSS Grid 筆記 12-Auto-Fit and Auto-Fill

設定 grid 的各項設定中, auto 還有 auto-fitauto-fill 兩種不同的設定,其差別在於 Explicit 的差異

Demo | Github

auto-fit and auto-fill

建立觀察兩者差異的 html 與 css 如下

1
2
3
4
5
6
<div class="container">
<div class="item item1">Item 01</div>
<div class="item item2">Item 02</div>
<div class="item item3">Item 03</div>
<div class="item item4">Item 04</div>
</div>
1
2
3
4
5
6
.container {
display: grid;
grid-gap: 20px;
border: 10px solid var(--yellow);
grid-template-columns: repeat(auto-fill, 150px);
}

主要可以觀察到最右邊的邊線在畫面接近卷軸的位置

auto-fill

這時候更換為 auto-fit ,其邊線位置只會按照內容項目的位置調整,就會在 item04 的右邊

auto-fit

兩者的差異就是 explicit 邊線的位置,所以這會有什麼影響?可以將 item04 的位置調整為固定在最後一欄,這時候兩者的差異就會造成當瀏覽器寬度不同時候的位置影響了。

1
2
3
.item4 {
grid-column-end: -1;
}

auto-fit column

筆記與備註事項

auto-fill

If the grid container has a definite or maximal size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container. Treating each track as its maximal track sizing function, if that is definite. Otherwise, as its minimum track sizing function, and taking grid-gap into account. If any number of repetitions would overflow, then the repetition is 1. Otherwise, if the grid container has a definite minimal size in the relevant axis, the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement. Otherwise, the specified track list repeats only once.
資料來源 - MDN

auto-fit

Behaves the same as auto-fill, except that after placing the grid items any empty repeated tracks are collapsed. An empty track is one with no in-flow grid items placed into or spanning across it. (This can result in all tracks being collapsed, if they’re all empty.)

A collapsed track is treated as having a fixed track sizing function of 0px, and the gutters on either side of it collapse.

For the purpose of finding the number of auto-repeated tracks, the user agent floors the track size to a user agent specified value (e.g., 1px), to avoid division by zero.
資料來源 - MDN

參考資料

歡迎關注我的其它發布渠道