這套 CSS 實用、強大且穩定,可立即使用。
我認為每位前端開發人員都應該瞭解如何使用容器查詢、建立捲動貼齊體驗、避免使用 position: absolute 搭配 grid、快速製作圓形、使用疊層,以及透過邏輯屬性以較少資源觸及更多使用者。以下簡要說明這些預期情形。
1. 容器查詢
連續 10 年來,開發人員最希望加入的 CSS 功能現在已在各瀏覽器中穩定運作,並於 2023 年推出,供您用於寬度查詢。
.panel {
container: layers-panel / inline-size;
}
.card {
padding: 1rem;
}
@container layers-panel (min-width: 20rem) {
.card {
padding: 2rem;
}
}
2. 捲動貼齊
精心設計的捲動體驗可讓您的應用程式與眾不同,而捲動快照是配合系統捲動使用者體驗的絕佳方式,同時提供有意義的停止點。
.snaps {
overflow-x: scroll;
scroll-snap-type: x mandatory;
overscroll-behavior-x: contain;
}
.snap-target {
scroll-snap-align: center;
}
.snap-force-stop {
scroll-snap-stop: always;
}
如要進一步瞭解這項 CSS 功能的潛力,請參閱這個龐大且令人振奮的 Codepen 集合,其中包含約 25 個示範。
scroll-snap-typescroll-snap-alignscroll-snap-stopoverscroll-behavior3. 格狀堆疊
避免使用單一儲存格 CSS 格線的絕對位置。將元素堆疊在一起後,請使用對齊和對齊屬性來放置元素。
.pile {
display: grid;
place-content: center;
}
.pile > * {
grid-area: 1/1;
}
grid4. 快速圓圈
在 CSS 中建立圓圈的方法有很多種,但這絕對是最簡潔的方式。
.circle { inline-size: 25ch; aspect-ratio: 1; border-radius: 50%; }
aspect-ratio5. 使用 @layer 控制變體
層疊層可協助將稍後發現或建立的變體插入層疊中的正確位置,並保留原始變體集。
/* file buttons.css */ @layer components.buttons { .btn.primary { … } }
然後,在某個完全不同的檔案中,於其他隨機時間載入,將新變體附加至按鈕層,就像它一直與其餘變體存在一樣。
/* file video-player.css */ @layer components.buttons { .btn.player-icon { … } }
@layer6. 使用邏輯屬性,減少記憶內容並觸及更多目標
請記住這個新盒裝模型,
再也不必擔心要為國際書寫模式和
文件方向變更左右邊框間距或邊界。
將樣式從實體屬性調整為邏輯屬性,例如
padding-inline、
margin-inline、
inset-inline,
瀏覽器就會自動調整。
button { padding-inline: 2ch; padding-block: 1ch; } article > p { text-align: start; margin-block: 2ch; } .something::before { inset-inline: auto 0; }