CSS Properties
CSS grid-gap Property
Photo Credit to CodeToFun
🙋 Introduction
The grid-gap
property in CSS is used to define the space between grid items in a CSS Grid layout.
This property is a shorthand for the grid-row-gap and grid-column-gap properties, allowing you to set the gaps between rows and columns simultaneously. It helps in creating well-spaced and visually appealing grid layouts.
💡 Syntax
The syntax for the grid-gap
property is straightforward and can accept one or two values.
.container {
grid-gap: row-gap column-gap;
}
- If one value is specified, it applies to both rows and columns.
- If two values are specified, the first value applies to the row gap, and the second value applies to the column gap.
🎛️ Default Value
The default value for the grid-gap
property is 0, meaning no gap between grid items.
🏠 Property Values
Value | Description |
---|---|
length | Specifies the size of the gap using any CSS length unit (e.g., px, em, rem, %). |
percentage | Specifies the size of the gap as a percentage of the grid container's size. |
📄 Example
In this example, we'll create a grid container with a 20px gap between both rows and columns.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS grid-gap Example</title>
<style>
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 20px;
}
.item {
background-color: #ff5733;
color: white;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<h1>Grid with Custom Gap</h1>
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
</div>
</body>
</html>
🖥️ Browser Compatibility
The grid-gap
property is supported in most modern browsers, including the latest versions of Chrome, Firefox, Safari, Edge, and Opera. However, it is always a good practice to test your website across different browsers to ensure compatibility.
🎉 Conclusion
The grid-gap
property is an essential tool for web developers working with CSS Grid layouts.
It simplifies the process of spacing grid items, enhancing the overall design and readability of your grid layouts. Experiment with different gap values to achieve the desired look and feel for your web projects.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (CSS grid-gap Property), please comment here. I will help you immediately.