CSS Grid
Design advanced layouts with CSS Grid, the most powerful layout system in CSS.
CSS Grid provides a two-dimensional layout system for web design. It allows you to design complex layouts more efficiently than traditional CSS methods.
🏗️ CSS Grid Basics
To create a grid container, use the display: grid property. This will enable the grid system on the parent element:
This establishes a grid context for the children of this container to be placed in a grid.
🎛️ Grid Template
You define rows and columns using the grid-template-columns and grid-template-rows properties. You can use these properties to specify how many rows and columns your grid will have, and their respective sizes.
Example: Define a 3-column grid with variable row heights
In this example:
repeat(3, 1fr)creates 3 equal-width columns.grid-template-rows: 100px 200px;defines 2 rows: the first row is 100px in height, and the second is 200px in height.
🧱 Grid Gaps and Spacing
To control the spacing between grid items, you can use the grid-gap (or gap in modern browsers) property:
Example: Add gaps between rows and columns
This will create a 20px gap between each grid item, both horizontally and vertically.
🗂️ Grid Item Placement
CSS Grid allows you to place grid items precisely where you want them using grid-column and grid-row.
Example: Place grid items in specific grid cells
In this example:
.item1spans from column 1 to column 3, and is placed in row 1..item2spans from column 2 to column 4, and is placed in row 2.
📱 Responsive Grids
CSS Grid is highly flexible and responsive. You can use auto-fill and auto-fit to create layouts that adjust automatically based on screen size.
Example: Create a responsive grid with a minimum width of 200px per column
repeat(auto-fill, minmax(200px, 1fr)): This will automatically fill as many columns as the container width allows, ensuring that each column has a minimum width of 200px, but will stretch to take up available space (up to 1fr, a flexible unit).
This results in a flexible and responsive grid layout that adapts to different screen sizes.
🧪 Try Yourself
In this example, you can see how the grid is defined with two equal-width columns (repeat(2, 1fr)). The gap property is used to add spacing between the items.
Key Points:
- CSS Grid is a 2D layout system, allowing you to design web pages with both rows and columns.
- Use
grid-template-columnsandgrid-template-rowsto define the structure of your grid. grid-gapcontrols the space between grid items.- Use
grid-columnandgrid-rowto place items exactly where you want them. - The grid is responsive, and
auto-fill/auto-fitcan help create flexible layouts.
With these basic concepts, you can now design complex and responsive layouts using CSS Grid!