CSS

Placing and Spanning Grid Items Across Multiple Tracks

Master how to precisely place CSS Grid items and make them occupy multiple columns or rows using `grid-column` and `grid-row` properties, enabling complex and flexible grid-based layouts.

.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: 15px;
  width: 90%;
  margin: 30px auto;
  border: 1px solid #ccc;
}

.grid-item {
  background-color: #d1e7dd;
  border: 1px solid #8bdcb6;
  padding: 10px;
  text-align: center;
  font-family: sans-serif;
  font-size: 1.2em;
}

.item-a {
  grid-column: 1 / 3; /* Spans from column line 1 to 3 (occupies 2 columns) */
  grid-row: 1;
  background-color: #cce5ff;
}

.item-b {
  grid-column: 4; /* Starts at column line 4, ends at auto */
  grid-row: 1 / 3; /* Spans from row line 1 to 3 (occupies 2 rows) */
  background-color: #ffeeba;
}

.item-c {
  grid-column: 2 / span 2; /* Starts at column line 2 and spans 2 columns */
  grid-row: 3;
  background-color: #f8d7da;
}

.item-d {
  grid-column: 1;
  grid-row: 2 / 4; /* Spans from row line 2 to 4 (occupies 2 rows) */
  background-color: #d4edda;
}
How it works: This snippet showcases the power of CSS Grid for precise item placement and sizing. `grid-template-columns` and `grid-template-rows` define the overall grid structure. Individual grid items can then be positioned and made to span multiple tracks using `grid-column` and `grid-row`. You can specify start/end lines (e.g., `1 / 3`) or use the `span` keyword (e.g., `span 2`) to make items cover a specific number of tracks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs