Create a Masonry Grid with CSS Grid Layout
Achieving a responsive grid layout where elements have variable heights but the same width can be challenging using flexbox or floats. Instead, consider utilizing the powerful CSS Grid Layout module.
CSS Grid Layout offers a flexible and efficient solution for creating complex grid layouts:
HTML Example:
<grid-container> <grid-item short></grid-item> <!-- ... more grid items --> </grid-container>
CSS Example:
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; } /* ... more grid item styles */
By applying these CSS rules, you can achieve a Masonry-like grid system where elements adjust their heights dynamically, ensuring a balanced and responsive layout.
The above is the detailed content of How to Create a Masonry Grid with CSS Grid Layout?. For more information, please follow other related articles on the PHP Chinese website!