CSS Grid 完整指南
CSS Grid 是現代網頁佈局的強大工具。這篇文章將帶您從基礎到進階,全面掌握 Grid 佈局。
Grid 基礎概念
Grid 是一個二維佈局系統,可以同時控制行和列。與 Flexbox 不同,Grid 專為二維佈局設計。
基本語法
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto;
gap: 20px;
}
Grid vs Flexbox
- Flexbox:適合一維佈局(行或列)
- Grid:適合二維佈局(行和列)
響應式設計
Grid 的 auto-fit 和 auto-fill 讓響應式設計變得非常簡單:
.grid {
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
實用技巧
- 使用
grid-area命名區域 - 利用
subgrid處理巢狀佈局 - 使用
minmax()創建彈性尺寸
瀏覽器支援
CSS Grid 在現代瀏覽器中都有良好的支援,是時候開始使用它了!