2024-09-09 web, development, javascript
CSS Grid in Action - Positioning Grid Items
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.
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:
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:
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:
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:
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!