CSS Masonry Grid with Flexbox or Other Layouts
Creating a grid layout in CSS where elements have varying heights can be challenging. While flexbox provides flexibility, it may not fulfill the requirement that newer elements align with the bottom of the previous one.
Introducing CSS Grid Layout
Instead of flexbox, consider leveraging CSS Grid Layout for this purpose. It offers a more robust and intuitive way to achieve a masonry grid:
HTML Structure:
<grid-container> <grid-item short></grid-item> <grid-item tall></grid-item> ... </grid-container>
CSS:
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; }
Explanation:
The above is the detailed content of How to Create a Masonry Grid Layout with Varying Heights in CSS?. For more information, please follow other related articles on the PHP Chinese website!