The CSS gap property defines the spacing (or "gap") between rows and columns in layouts such as Flexbox, Grid, or multi-column layouts. It simplifies the process of creating consistent spacing by combining row-gap and column-gap into one property. You can specify the gap using length units (e.g., px, em) or percentages.
Syntax:
gap: <row-gap> <column-gap>- row-gap: Defines the gap between rows.
- column-gap: Defines the gap between columns.
Property Values
| Property Value | Description |
|---|---|
| <length> | Specifies the spacing using length units like em, px, etc. For example: gap: 10px 20px. |
| <percentage> | Specifies the spacing using percentage units. For example: gap: 50%. |
CSS gap Property Examples
Here are examples of the CSS gap property to illustrate its use in layouts:
Example 1: Using Length Units
In this example we are using CSS Grid with specified row and column gaps (gap: 20px 50px) for layout spacing between grid items (col divs).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<style>
.row {
display: grid;
width: 500px;
gap: 20px 50px;
}
.col {
background-color: green;
border: 1px solid black;
color: #fff;
width: fit-content;
height: 20px;
font-size: 20px;
}
</style>
</head>
<body>
<div class="row">
<div class="col">
geeksforgeeks
</div>
<div class="col">
geeksforgeeks
</div>
<div class="col">
geeksforgeeks
</div>
</div>
<div class="row">
<div class="col">
geeksforgeeks
</div>
<div class="col">
geeksforgeeks
</div>
<div class="col">
geeksforgeeks
</div>
</div>
</body>
</html>
Output:
Example 2: Using Percentage Units
In this example we are using CSS Grid with a row gap specified as a percentage (gap: 20%) for layout spacing between grid items (col divs) within each row (row divs).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<style>
.row {
display: grid;
width: fit-content;
gap: 20%;
height: 100px;
background-color: greenyellow;
}
.col {
background-color: green;
border: 1px solid black;
color: #fff;
width: fit-content;
font-size: 20px;
}
</style>
</head>
<body>
<p>In terms of percentage</p>
<div class="row">
<div class="col">
geeksforgeeks
</div>
<div class="col">
geeksforgeeks
</div>
<div class="col">
geeksforgeeks
</div>
</div>
<br><br><br>
<div class="row">
<div class="col">
geeksforgeeks
</div>
<div class="col">
geeksforgeeks
</div>
<div class="col">
geeksforgeeks
</div>
</div>
</body>
</html>
Output:
Note: Older browser versions may have limited support, so it’s always recommended to test for compatibility across different browsers.