How to Create a Masonry Grid Layout with Varying Heights in CSS?

Linda Hamilton
Release: 2024-11-26 00:33:15
Original
529 people have browsed it

How to Create a Masonry Grid Layout with Varying Heights in CSS?

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

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

Explanation:

  1. display: grid: Initializes the container as a grid layout.
  2. grid-auto-rows: 50px: Sets the height of each grid row to 50 pixels.
  3. grid-gap: 10px: Specifies the spacing between grid items.
  4. grid-template-columns: Defines how many columns are in the grid (auto-fill) and the minimum width for each column (min-content: 30%, 1fr).
  5. grid-row: span X: Indicates that the item should occupy X number of grid rows.

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template