CSS grid-row-gap property
The grid-row
property in CSS is used to specify how a grid item should span across rows in a grid container. It allows you to control the starting and ending positions of a grid item within the grid's row tracks. This property helps you manage the vertical placement and size of grid items.
Basic Syntax
selector {
grid-row: start / end;
}
Example
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
grid-template-rows: 100px 200px 100px; /* Three rows */
grid-gap: 10px; /* Space between grid items */
}
.item1 {
grid-row: 1 / 3; /* Spans from row line 1 to row line 3 */
background-color: lightcoral;
padding: 20px;
}
.item2 {
grid-row: 2 / 4; /* Spans from row line 2 to row line 4 */
background-color: lightblue;
padding: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="item1">Item 1</div>
<div class="item2">Item 2</div>
</div>
</body>
</html>
In this example, .item1
spans from the first row line to the third row line, covering two rows, while .item2
spans from the second row line to the fourth row line, also covering two rows.
Values for grid-row
1. Start and End Line Numbers
You can specify the grid lines where the item should start and end.
grid-row: 1 / 3; /* Starts at the first row line and ends at the third row line */
2. Span Keyword
You can use the span
keyword to specify how many rows the item should span.
grid-row: span 2; /* Spans across 2 rows */
3. Auto Placement
If only one value is provided, it defines the starting line, and the item will span to the end of the grid.
grid-row: 2; /* Starts at row line 2 and spans to the end of the grid */
4. Grid Area Placement
You can also use the grid-row
property with grid-template-areas
to position items based on named areas.
.grid-item {
grid-row: header;
}
Practical Examples
Example 1: Spanning Multiple Rows
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
grid-template-rows: 100px 200px 100px; /* Three rows */
grid-gap: 10px; /* Space between grid items */
}
.item1 {
grid-row: 1 / 3; /* Spans from row line 1 to 3 */
background-color: lightcoral;
padding: 20px;
}
.item2 {
grid-row: 2 / 4; /* Spans from row line 2 to 4 */
background-color: lightblue;
padding: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="item1">Item 1</div>
<div class="item2">Item 2</div>
</div>
</body>
</html>
Example 2: Spanning Rows with span
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
grid-template-rows: 100px 100px 100px 100px; /* Four rows */
grid-gap: 10px; /* Space between grid items */
}
.item {
background-color: lightcoral;
padding: 20px;
}
.item1 {
grid-row: span 2; /* Spans 2 rows */
}
.item2 {
grid-row: span 3; /* Spans 3 rows */
}
</style>
</head>
<body>
<div class="container">
<div class="item item1">Item 1</div>
<div class="item item2">Item 2</div>
</div>
</body>
</html>