CSS网格布局的优势在于可以将页面分割成大块的区域,或者定义由HTML元素构建出的控件的大小、位置和图层之间的关系。
和表格类似,网格布局允许作者将元素对其到行或者列。但是,许多的布局要么不可能实现要么不像用表格实现起来那么方便。例如,一个网格容器的子元素可以自己定位,以便它们像CSS定位的元素一样,真正的有重叠和层次。
基本示例
以下示例显示了一个三列轨道网格,其中创建的行数最小为100像素,最大为自动。条目已经使用基线位置放置在网格上。
* {box-sizing: border-box;} .wrapper { max-width: 940px; margin: 0 auto; } .wrapper > div { border: 2px solid rgb(233,171,88); border-radius: 5px; background-color: rgba(233,171,88,.5); padding: 1em; color: #d9480f; }
HTML
<div class="wrapper"> <div class="one">One</div> <div class="two">Two</div> <div class="three">Three</div> <div class="four">Four</div> <div class="five">Five</div> <div class="six">Six</div> </div>
CSS
.wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 10px; grid-auto-rows: minmax(100px, auto); } .one { grid-column: 1 / 3; grid-row: 1; } .two { grid-column: 2 / 4; grid-row: 1 / 3; } .three { grid-row: 2 / 5; grid-column: 1; } .four { grid-column: 3; grid-row: 3; } .five { grid-column: 2; grid-row: 4; } .six { grid-column: 3; grid-row: 4; }
参考
CSS properties
CSS function
Glossary entries
指南
- Basic concepts of Grid Layout
- Relationship of Grid Layout to other layout methods
- Layout using named grid lines
- Grid template areas
- Layout using named grid lines
- Auto-placement in CSS Grid Layout
- Box alignment in CSS Grid Layout
- CSS Grid, Logical Values and Writing Modes
- CSS Grid Layout and accessibility
- CSS Grid and progressive enhancement
- Realising common layouts using CSS Grid
外部资源
- Examples from Jen Simmons
- Grid by Example - a collection of usage examples and video tutorials
- Codrops Grid Reference
- Firefox DevTools CSS Grid Inspector
规范
Specification | Status | Comment |
---|---|---|
CSS Grid Layout | Candidate Recommendation | Initial definition. |