How to Create a Masonry Grid Effect with CSS Grid Layout?

DDD
Release: 2024-11-19 00:58:02
Original
664 people have browsed it

How to Create a Masonry Grid Effect with CSS Grid Layout?

Create a CSS Grid Layout for a Masonry Grid Effect

The Challenge: Uneven Height Grid Elements

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.

The Solution: CSS Grid Layout

For optimal performance, consider utilizing CSS Grid Layout, a powerful tool specifically designed to handle complex grid layouts:

  1. Define Grid Properties (grid-container): Start by defining the grid container with display: grid. Set grid-auto-rows to the desired default row height (e.g., 50px). grid-gap controls the spacing between grid elements.
  2. Set Columns Automatically (grid-template-columns): Use repeat(auto-fill, minmax(30%, 1fr)) to create columns that automatically adjust their width based on available space. The 30% minimum ensures elements have sufficient width.
  3. Adjust Row Span (grid-row): Use the grid-row property on individual elements to determine how many rows they occupy. Simply specify span 1, span 2, etc., according to the desired height.

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template