QP School

Full Version: CSS Grid Masonry Layout
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Description:

CSS Grid can be used to create a masonry layout, where items are arranged in columns with varying heights to create an asymmetrical grid.

Example:

<!DOCTYPE html>
<html>
<head>
  <title>CSS Grid Masonry Layout Example</title>
  <style>
    .masonry-container {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      grid-gap: 10px;
    }
    .masonry-item {
      background-color: lightblue;
      padding: 10px;
    }
    .item1 {
      grid-row-end: span 2; /* This item will span 2 rows */
    }
    .item3 {
      grid-row-end: span 3; /* This item will span 3 rows */
    }
  </style>
</head>
<body>
  <div class="masonry-container">
    <div class="masonry-item item1">1<br>First item</div>
    <div class="masonry-item">2<br>Second item</div>
    <div class="masonry-item item3">3<br>Third item</div>
    <div class="masonry-item">4<br>Fourth item</div>
    <div class="masonry-item">5<br>Fifth item</div>
    <!-- Add more items here -->
  </div>
</body>
</html>

Explanation:

In this example, the .masonry-container creates a masonry layout using CSS Grid. The grid-template-columns property with repeat(auto-fit, minmax(200px, 1fr)) creates flexible columns that adjust according to the available space, with a minimum of 200px and a maximum of 1fr (equal share of the available space). The .masonry-item divs have varying heights and are arranged in columns, creating a masonry-style layout.

These additional examples showcase more advanced and lesser-known CSS3 features that can be applied creatively to enhance your web designs. As with any new feature, it's essential to check for browser support and consider fallbacks for older browsers if necessary. CSS3 continues to evolve, so keep exploring and experimenting to create cutting-edge web designs.