CSS

Spanning Multiple Rows or Columns in CSS Grid

Learn to control grid item placement and size by spanning multiple rows or columns using `grid-column` and `grid-row` properties in CSS Grid layouts for complex designs.

.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 4 equal columns */
  grid-template-rows: repeat(3, 100px); /* 3 rows, each 100px tall */
  gap: 10px;
  border: 1px solid #333;
  padding: 10px;
  width: 500px;
}

.grid-item {
  background-color: lightblue;
  border: 1px solid blue;
  padding: 10px;
  text-align: center;
}

.item-a {
  /* Starts at column line 1, spans 2 columns */
  grid-column: 1 / span 2;
  /* Can also be written as grid-column: 1 / 3; */
  background-color: lightcoral;
}

.item-b {
  /* Starts at row line 1, spans 3 rows */
  grid-row: 1 / span 3;
  /* Can also be written as grid-row: 1 / 4; */
  background-color: lightgreen;
}

.item-c {
  /* Starts at column line 3, spans 2 columns */
  grid-column: 3 / span 2;
  /* Starts at row line 2, spans 2 rows */
  grid-row: 2 / span 2;
  background-color: orange;
}

/* Example HTML structure */
/*
<div class="grid-container">
  <div class="grid-item item-a">Item A (col span 2)</div>
  <div class="grid-item item-b">Item B (row span 3)</div>
  <div class="grid-item item-c">Item C (col span 2, row span 2)</div>
  <div class="grid-item">Item D</div>
  <div class="grid-item">Item E</div>
  <div class="grid-item">Item F</div>
  <div class="grid-item">Item G</div>
</div>
*/
How it works: CSS Grid provides powerful properties to explicitly place and size grid items across multiple rows and columns. The `grid-column` and `grid-row` properties allow you to define where an item starts and how many tracks it spans. You can specify start and end lines (e.g., `1 / 3` for lines 1 to 3) or use the `span` keyword (e.g., `span 2`) to indicate how many tracks an item should occupy, enabling the creation of complex, non-uniform grid layouts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs