此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
grid-auto-flow
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2017年10月.
grid-auto-flow 属性控制着自动布局算法怎样运作,精确指定在网格中被自动布局的元素怎样排列。
In this article
尝试一下
grid-auto-flow: row;grid-auto-flow: column;grid-auto-flow: row dense;<section> <div> <div> <div>One</div> <div>Two</div> <div>Three</div> <div>Four</div> <div>Five</div> </div> </div></section>#example-element { border: 1px solid #c5c5c5; display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: repeat(3, minmax(40px, auto)); grid-gap: 10px; width: 220px;}#example-element > div { background-color: rgba(0, 0, 255, 0.2); border: 3px solid blue;}#example-element > div:nth-child(1) { grid-column: auto / span 2;}#example-element > div:nth-child(2) { grid-column: auto / span 2;}语法
css
/* Keyword values */grid-auto-flow: row;grid-auto-flow: column;grid-auto-flow: dense;grid-auto-flow: row dense;grid-auto-flow: column dense;/* Global values */grid-auto-flow: inherit;grid-auto-flow: initial;grid-auto-flow: unset;此属性有两种形式:
- 单个关键字:
row、column,或dense中的一个。 - 两个关键字:
row dense或column dense。
取值
正式语法
grid-auto-flow =
[row|column]||
dense
示例
>HTML
html
<div> <div></div> <div></div> <div></div> <div></div> <div></div></div><select onchange="changeGridAutoFlow()"> <option value="column">column</option> <option value="row">row</option></select><input type="checkbox" onchange="changeGridAutoFlow()" /><label for="dense">dense</label>CSS
css
#grid { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); grid-auto-flow: column; /* or 'row', 'row dense', 'column dense' */}#item1 { background-color: lime; grid-row-start: 3;}#item2 { background-color: yellow;}#item3 { background-color: blue;}#item4 { grid-column-start: 2; background-color: red;}#item5 { background-color: aqua;}function changeGridAutoFlow() { var grid = document.getElementById("grid"); var direction = document.getElementById("direction"); var dense = document.getElementById("dense"); var gridAutoFlow = direction.value === "row" ? "row" : "column"; if (dense.checked) { gridAutoFlow += " dense"; } grid.style.gridAutoFlow = gridAutoFlow;}规范
| Specification |
|---|
| CSS Grid Layout Module Level 2> # grid-auto-flow-property> |
浏览器兼容性
参见
- Related CSS properties:
grid-auto-rows,grid-auto-columns,grid - Grid Layout Guide:Auto-placement in grid layout
- Video tutorial:Introducing Grid auto-placement and order