CSS Grid in Action - Positioning Grid Items

2023-10-12
By: O. Wolfson

Introduction

Now that you've set up a grid container, the real fun begins: positioning your grid items. Whether you want a simple layout or a more intricate one, CSS Grid offers a versatile set of properties to get you there. Let's delve into the world of grid item positioning!


1. The Basics of Grid Item Positioning

Each grid item can span multiple rows and/or columns. You define this by specifying where they start and end in relation to the grid lines.


2. Grid Column and Row Start and End

Using the grid-column-start, grid-column-end, grid-row-start, and grid-row-end properties, you can define the starting and ending points of your grid items.

css
.itemA {
  grid-column-start: 1;
  grid-column-end: 3;
}

This means that itemA will start from the first vertical grid line and span until the third, covering two columns.


3. Shorthand for Columns and Rows

Instead of using four separate properties, you can utilize shorthand to achieve the same result:

css
.itemB {
  grid-column: 1 / 3; /* Starts at the first and ends at the third vertical grid line */
  grid-row: 2 / 4; /* Starts at the second and ends at the fourth horizontal grid line */
}

4. The Magic of grid-area

The grid-area property serves as a shorthand for the aforementioned properties, allowing you to specify the row and column start/end in one go:

css
.itemC {
  grid-area: 2 / 1 / 4 / 3; /* grid-row-start / grid-column-start / grid-row-end / grid-column-end */
}

With grid-area, itemC begins at the second row and first column and spans up to the fourth row and third column.


5. Spanning Multiple Rows or Columns

If you want an item to span multiple rows or columns, simply use the span keyword:

css
.itemD {
  grid-column: span 2; /* Spans two columns */
  grid-row: span 3; /* Spans three rows */
}

Here, itemD will cover two columns and three rows from its starting position.


6. Practical Example: The Grid Overlay

Let's visualize this with an example:

html
<div class="container">
  <div class="item itemA">A</div>
  <div class="item itemB">B</div>
  <div class="item itemC">C</div>
  <div class="item itemD">D</div>
  <div class="item itemE">E</div>
</div>
css
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}
.item {
  background-color: #eee;
  padding: 20px;
  text-align: center;
}
.itemA {
  grid-column: 1 / 3;
}
.itemB {
  grid-row: 2 / 4;
}
.itemC {
  grid-area: 3 / 2 / 4 / 3;
}
.itemD {
  grid-column: span 2;
  grid-row: span 3;
}

Conclusion

Positioning grid items is essential in harnessing the full power of CSS Grid. The properties discussed above enable intricate designs and allow for a high degree of customization in your layouts.

Up Next: In our next segment, we'll deep dive into grid gaps, alignment, and much more. See you then!