Technology Sharing

【CSS】Abbreviation attribute gap

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

In CSS Grid Layout and Flexbox,gap is a shorthand property for setting the size of both the row gutter and the column gutter (often called "cross axis gap" in Flexbox). This greatly simplifies the previous practice of setting the gutter separately.row-gap(or grid-row-gap In older versions of CSS Grid) andcolumn-gap(or grid-column-gap) is a cumbersome process.

Use in Grid Layout

In CSS Grid Layout,gap The property can set the size of the gaps between both grid rows and grid columns.

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 创建三个等宽的列 */
  gap: 20px; /* 同时设置行和列间隙为20px */
  /* 或者更具体地 */
  /* gap: 20px 30px; /* 第一个值设置行间隙,第二个值设置列间隙 */
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Using Flexbox

In Flexbox,gap The properties are used to set the gaps between flex items. This includes gaps on both the main axis and the cross axis (although in Flexbox, the concept of cross-axis gaps may not be as intuitive as in Grid, as it primarily affects the layout of multi-line flex containers).

.flex-container {
  display: flex;
  flex-wrap: wrap; /* 允许flex项换行 */
  gap: 10px; /* 同时设置主轴和交叉轴上的间隙为10px */
  /* 或者更具体地 */
  /* row-gap: 10px; /* 仅在需要时设置行间隙 */
  /* column-gap: 15px; /* 仅在需要时设置列间隙(或交叉轴间隙),但这在Flexbox中通常不太常见 */
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Please note,gap The value of the attribute can be a length (such aspxemvw etc.), percentage or any otherrow-gapandcolumn-gapIn addition, if you need torow-gapandcolumn-gapTo set different values, you can use these two values ​​asgapThe first value corresponds to the row gap, and the second value corresponds to the column gap (in Grid) or the cross-axis gap (in Flexbox, although this is less common).

It is worth noting that althoughgapThe property is widely supported in recent browser versions, but you should still consider backward compatibility when writing CSS and may need to use-webkit-prefix (for some older browsers) or provide a fallback.