grid-template-areas
CSS 属性是网格区域 grid areas 在CSS中的特定命名。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Those areas are not associated with any particular grid item, but can be referenced from the grid-placement properties grid-row-start
, grid-row-end
, grid-column-start
, grid-column-end
, and their shorthands grid-row
, grid-column
, and grid-area
.
网格区块(grid areas)和网格项(grid item)沒有关联,但是它们可以和一些网格定位属性(grid-placement properties)关联起来,比如grid-row-start
, grid-row-end
, grid-column-start
和grid-column-end
;也可以和一些速记(shorthands)属性关联起来,比如grid-row
,grid-column
和 grid-area
。
Syntax[语法]
/* Keyword value */
grid-template-areas: none;
/* <string> values */
grid-template-areas: "a b"; /* 一行 两列 */
grid-template-areas: "a b b"
"a c d"; /* 两行 三列 */
/* Global values */
grid-template-areas: inherit; /* 继承 */
grid-template-areas: initial; /* 默认值 */
grid-template-areas: unset; /* 未设置 */
Values[可选值]
none
- 网格容器没有定义任何的网格区块(grid areas)。
<string>
+- 每一个给定的字符串会生成一行,一个字符串中用空格分隔的每一个单元(cell)会生成一列。多个同名的,跨越相邻行或列的单元称为网格区块(grid area)。非矩形的网格区块是无效的。
形式化语法
例子
HTML
<section id="page">
<header>Header</header>
<nav>Navigation</nav>
<main>Main area</main>
<footer>Footer</footer>
</section>
CSS
#page {
display: grid; /* 1.设置display为grid */
width: 100%;
height: 250px;
grid-template-areas: "head head"
"nav main"
"nav foot"; /* 2.区域划分 当前为 三行 两列 */
grid-template-rows: 50px 1fr 30px; /* 3.各区域 宽高设置 */
grid-template-columns: 150px 1fr;
}
#page > header {
grid-area: head; /* 4. 指定当前元素所在的区域位置, 从grid-template-areas选取值 */
background-color: #8ca0ff;
}
#page > nav {
grid-area: nav;
background-color: #ffa08c;
}
#page > main {
grid-area: main;
background-color: #ffff64;
}
#page > footer {
grid-area: foot;
background-color: #8cffa0;
}
结果
规范
规范 | 状态 | 说明 |
---|---|---|
CSS Grid Layout grid-template-areas |
Candidate Recommendation | Initial definition |
初始值 | none |
---|---|
适用元素 | grid containers |
是否是继承属性 | 否 |
计算值 | as specified |
Animation type | discrete |
浏览器兼容性
BCD tables only load in the browser
[1] 从Chrome 29.0 开始支持,在 chrome://flags
中打开"开启实验性网络平台特性"(experimental Web Platform features)。从 Chrome 57.0 开始默认开启。
[2] 从Gecko 40.0 (Firefox 40.0 / Thunderbird 40.0 / SeaMonkey 2.37) 开始支持, 在设置中打开layout.css.grid.enabled
,默认是 false
。从Gecko 52.0 (Firefox 52.0 / Thunderbird 52.0 / SeaMonkey 2.49)开始默认开启。
[3] EdgeHTML 16已支持。Internet Explorer 和 Edge 实现了一个旧版本的规范,旧的规范中没有定义这个属性。
[4] 从 Opera 28.0开始支持,在 chrome://flags
中打开"开启实验性网络平台特性"(experimental Web Platform features)。从Opera 44开始默认开启。
See also
- 相关 CSS 属性:
grid-template-rows
、grid-template-columns
、grid-template
- Grid Layout 指南:Grid template areas
- 视频教程:Grid Template Areas