CSS

Span Grid Items Across Multiple Rows and Columns

Master placing and spanning elements across specific columns and rows in a CSS Grid layout using `grid-column` and `grid-row` properties for precise control.

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
  grid-template-rows: repeat(2, 100px); /* 2 rows, 100px height */
  gap: 15px;
  width: 80%;
  margin: 30px auto;
  background-color: #e0f7fa;
  padding: 20px;
  border: 1px solid #b2ebf2;
}

.grid-item {
  background-color: #00bcd4;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: sans-serif;
  font-size: 1.2em;
  border-radius: 5px;
}

/* Item 1 spans 2 columns */
.item-1 {
  grid-column: span 2;
}

/* Item 3 spans 2 rows */
.item-3 {
  grid-row: span 2;
}

/* Item 5 starts at column 2 and spans 2 columns */
.item-5 {
  grid-column: 2 / span 2; /* or grid-column: 2 / 4; */
}

<div class="grid-container">
  <div class="grid-item item-1">Item 1 (span 2 cols)</div>
  <div class="grid-item item-2">Item 2</div>
  <div class="grid-item item-3">Item 3 (span 2 rows)</div>
  <div class="grid-item item-4">Item 4</div>
  <div class="grid-item item-5">Item 5 (start col 2, span 2 cols)</div>
</div>
How it works: This snippet showcases how to control the placement and spanning of individual items within a CSS Grid layout. `grid-template-columns` and `grid-template-rows` define the base grid structure. Using `grid-column: span X` or `grid-row: span Y` allows an item to occupy multiple tracks. You can also specify a starting line (e.g., `grid-column: 2 / span 2`) for even more precise placement. This technique is crucial for designing complex, non-uniform layouts where certain elements need to stretch across different parts of the grid.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs