gap (grid-gap)

CSS gap 属性是用来设置网格行与列之间的间隙(gutters),该属性是 row-gapcolumn-gap 的简写形式。

尝试一下

语法

css
/* One <length> value */
gap: 20px;
gap: 1em;
gap: 3vmin;
gap: 0.5cm;

/* One <percentage> value */
gap: 16%;
gap: 100%;

/* Two <length> values */
gap: 20px 10px;
gap: 1em 0.5em;
gap: 3vmin 2vmax;
gap: 0.5cm 2mm;

/* One or two <percentage> values */
gap: 16% 100%;
gap: 21px 82%;

/* calc() values */
gap: calc(10% + 20px);
gap: calc(20px + 10%) calc(10% - 5px);

/* Global values */
gap: inherit;
gap: initial;
gap: revert;
gap: revert-layer;
gap: unset;

该属性用来表示 <'row-gap'><'column-gap'> 的值(<'column-gap'> 是可选的)。假如 <'column-gap'> 缺失的话,则会被设置成跟 <'row-gap'> 一样的值。

<'row-gap'><'column-gap'> 都可以用 <length> 或者 <percentage> 来表示。

<length>

网格线之间的间隙宽度。

<percentage>

网格线直接的间隙宽度,相对网格容器的百分比。

形式定义

初始值as each of the properties of the shorthand:
适用元素multi-column elements, flex containers, grid containers
是否是继承属性
计算值as each of the properties of the shorthand:
  • row-gap: as specified, with <length>s made absolute, and normal computing to zero except on multi-column elements
  • column-gap: as specified, with <length>s made absolute, and normal computing to zero except on multi-column elements
Animation typeas each of the properties of the shorthand:

形式语法

gap = 
<'row-gap'> <'column-gap'>?

示例

Flex 布局

HTML

html
<div id="flexbox">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

CSS

css
#flexbox {
  display: flex;
  flex-wrap: wrap;
  width: 300px;
  gap: 20px 5px;
}

#flexbox > div {
  border: 1px solid green;
  background-color: lime;
  flex: 1 1 auto;
  width: 100px;
  height: 50px;
}

结果

Grid 布局

HTML

html
<div id="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

CSS

css
#grid {
  display: grid;
  height: 200px;
  grid-template: repeat(3, 1fr) / repeat(3, 1fr);
  gap: 20px 5px;
}

#grid > div {
  border: 1px solid green;
  background-color: lime;
}

结果

多列布局

HTML

html
<p class="content-box">
  This is some multi-column text with a 40px column gap created with the CSS
  <code>gap</code> property. Don't you think that's fun and exciting? I sure do!
</p>

CSS

css
.content-box {
  column-count: 3;
  gap: 40px;
}

结果

规范

Specification
CSS Box Alignment Module Level 3
# gap-shorthand

浏览器兼容性

BCD tables only load in the browser

参见