1. 面向开发者的 Web 技术
  2. CSS:层叠样式表
  3. 网格布局

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

网格布局

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, 0.5);
 padding: 1em;
 color: #d9480f;
}

HTML

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

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 属性

CSS 函数

CSS 数据类型

术语表

指南

外部资源

规范

Specification
CSS Grid Layout Module Level 2

Help improve MDN

Learn how to contribute

This page was last modified on by MDN contributors.

AltStyle によって変換されたページ (->オリジナル) /