Home >Web Front-end >CSS Tutorial >How to Create a Masonry Grid with CSS Grid Layout?

How to Create a Masonry Grid with CSS Grid Layout?

Barbara Streisand
Barbara StreisandOriginal
2024-11-20 04:54:02881browse

How to Create a Masonry Grid with CSS Grid Layout?

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:

  1. Display: Set the container element to display: grid to indicate it's a grid container.
  2. Grid Auto-Rows: Specify the consistent height for the grid rows using grid-auto-rows: 50px. This sets the default height for each row.
  3. Grid Gap: Add spacing between grid items with grid-gap: 10px.
  4. Grid Template Columns: define the column layout using grid-template-columns: repeat(auto-fill, minmax(30%, 1fr)). This creates a grid with columns of at least 30% width, filling the remaining space evenly.
  5. Spanning Rows: Use the grid-row property on individual grid items to control how many rows they span. For instance, [tall] spans two rows, while [tallest] spans four.

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!

Statement:
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