Home >Web Front-end >CSS Tutorial >How can I create a masonry grid using CSS Grid Layout with elements of varying heights?
Creating Masonry Grids with CSS Grid Layout
In CSS, achieving a grid effect with elements of varying heights can be challenging. However, the recently introduced CSS Grid Layout offers a powerful solution.
Using CSS Grid Layout
To create a masonry grid using CSS Grid Layout, you can follow these steps:
Implementing Masonry Grid
Here's an example HTML and CSS code to create a masonry grid:
<grid-container> <grid-item short></grid-item> <grid-item short></grid-item> <grid-item tall></grid-item> <grid-item tall></grid-item> <grid-item short></grid-item> <grid-item taller></grid-item> <grid-item short></grid-item> <grid-item tallest></grid-item> <grid-item tall></grid-item> <grid-item short></grid-item> <grid-item tallest></grid-item> <grid-item tall></grid-item> <grid-item taller></grid-item> <grid-item short></grid-item> <grid-item short></grid-item> <grid-item short></grid-item> <grid-item short></grid-item> <grid-item tall></grid-item> <grid-item short></grid-item> <grid-item taller></grid-item> <grid-item short></grid-item> <grid-item tall></grid-item> <grid-item short></grid-item> <grid-item tall></grid-item> <grid-item short></grid-item> <grid-item short></grid-item> <grid-item tallest></grid-item> <grid-item taller></grid-item> <grid-item short></grid-item> <grid-item tallest></grid-item> <grid-item tall></grid-item> <grid-item short></grid-item> </grid-container>
grid-container { display: grid; grid-auto-rows: 50px; grid-gap: 10px; grid-template-columns: repeat(auto-fill, minmax(30%, 1fr)); } [short] { grid-row: span 1; background-color: green; } [tall] { grid-row: span 2; background-color: crimson; } [taller] { grid-row: span 3; background-color: blue; } [tallest] { grid-row: span 4; background-color: gray; }
This code will create a masonry grid where elements of different heights are automatically laid out in an evenly spaced, grid-like structure.
The above is the detailed content of How can I create a masonry grid using CSS Grid Layout with elements of varying heights?. For more information, please follow other related articles on the PHP Chinese website!