To achieve a masonry grid effect, you want elements of varying heights to align perfectly without affecting the element's position below. However, traditional methods like floats or flexbox may not fully meet this requirement.
For optimal performance, consider utilizing CSS Grid Layout, a powerful tool specifically designed to handle complex grid layouts:
For example:
.container { display: grid; grid-auto-rows: 50px; grid-gap: 10px; grid-template-columns: repeat(auto-fill, minmax(30%, 1fr)); } .short { grid-row: span 1; } .tall { grid-row: span 2; } .taller { grid-row: span 3; } .tallest { grid-row: span 4; }
This code will create a grid where elements automatically vary in width without affecting the alignment of the grid. Each element's height is determined by its designated row span.
The above is the detailed content of How to Create a Masonry Grid Effect with CSS Grid Layout?. For more information, please follow other related articles on the PHP Chinese website!