CSS

Control Grid Item Placement and Spanning with `grid-column` and `grid-row`

Control explicit grid item positioning and spanning across multiple rows or columns using `grid-column`, `grid-row` for precise layout design.

.grid-layout {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 4 equal columns */
  grid-template-rows: repeat(3, 100px);   /* 3 rows, 100px height */
  gap: 10px;
  max-width: 600px;
  margin: 20px auto;
  border: 1px solid #ccc;
  padding: 10px;
}

.grid-item {
  background-color: #d1e7dd;
  border: 1px solid #a3cfb5;
  padding: 15px;
  text-align: center;
}

/* Item 1: Starts at column 1, spans 2 columns */
.item-1 {
  grid-column: 1 / span 2;
  grid-row: 1;
  background-color: #f8d7da;
}

/* Item 2: Starts at row 2, spans 2 rows */
.item-2 {
  grid-column: 4;
  grid-row: 2 / span 2;
  background-color: #fff3cd;
}

/* Item 3: Starts at column 2, goes to end of 3rd column line */
.item-3 {
  grid-column: 2 / 4; /* Spans from line 2 to line 4 (exclusive) */
  grid-row: 3;
  background-color: #cfe2ff;
}
How it works: This snippet illustrates how to precisely position and size individual items within a CSS Grid layout using `grid-column` and `grid-row`. You can define where an item starts and how many columns or rows it spans, either by line numbers (e.g., `1 / 3` for start line 1, end line 3) or by using `span X` (e.g., `span 2` to span two tracks). This offers granular control over layout when `grid-template-areas` or auto-placement isn't sufficient.

Need help integrating this into your project?

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

Hire DigitalCodeLabs