After learning theoretical concepts of grid, let's apply our knowledge to real-world examples.
Table of contents
- Responsive layout with grid without media-queries
- Responsive layout with grid with media-queries
- Overlapping items with grid
- Grid vs Flexbox
Responsive layout with grid
Without media queries
When we talked about auto-fill
and auto-fit
in "track sizes", we encountered a way to make grid layout responsive without using media queries
:
ul {
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
Here, the list depends on the browser width: if items with 300px width can't fit in one row, they will be placed in the next row.
With media queries
We start creating the layout for mobile phones first, then for devices with a width larger than 500px
and at the end for a width larger than700px
. At different breakpoints, we change grid-template-areas
and grid-template-columns
:
Overlapping items with grid
To overlap items, we usually change the position
of the elements, while we can do that with grid
by specifying grid areas that items will occupy:
In case we need to change the stacking context of the elements (so the element will be on top of others) ,
z-index
comes in handy.
Grid vs Flexbox
The main difference between these two layouts is in who controls the sizing. In grid, the container defines sizes of columns and rows, while for flexbox (with flex-wrap: wrap
to make it "two-dimensional"), this power lies with the content. Flexbox children define how much space they can occupy. If we don't want this flexibility, it's better to use grid:
Top comments (0)