Responsive Masonry Layouts with CSS Grid and Mason-it.js

Responsive Masonry Layouts with CSS Grid and Mason-it.js
Mason-it is a lightweight JavaScript library that transforms CSS Grid powered layout into a responsive masonry layout while preserving your original grid design.

Many developers, myself included, have reached for CSS Grid to build layouts, only to find that most masonry libraries want to dictate their own positioning, often ignoring grid-template-columns or gap. mason-it takes a different approach: you define the grid, and it handles the vertical stacking.

Features

  • True CSS Grid Based: It works directly with your display: grid container and its properties like grid-template-columns and gap.
  • Zero Dependencies: Just a small JavaScript file (around 6KB minified and gzipped). No extra baggage.
  • Simple API: Can be initialized with a single data-mason-it HTML attribute or a JavaScript call: MasonIt.init().
  • Dynamic Content Ready: Uses MutationObserver to automatically detect and adjust for items added or removed from the grid.
  • Smooth Updates: Leverages requestAnimationFrame for fluid layout recalculations on content changes or window resize.
  • Handles Hidden Elements: Correctly recalculates layouts when items with display: none become visible or vice-versa.
  • Fast & Responsive: Recalculates quickly, aiming for a native feel.
  • Image Load Aware (indirectly): While it doesn’t have a built-in “images loaded” checker, it’s designed to work correctly if refreshed after images load, and its internal logic waits for content to be ready before initial calculation.

How to use it:

1. Install Mason-it and import it into your project.

# NPM
$ npm install mason-it
import MasonIt from 'mason-it';
<!-- OR -->
<script src="/dist/mason-it.min.js"></script>

2. For mason-it to work as intended, your grid container needs a specific CSS property:

.my-masonry-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); /* Your column setup */
  gap: 15px; /* Your desired gap */
  align-items: start; /* Essential! Prevents items from stretching to fill row height */
  /* grid-auto-rows: min-content; */ /* Optional, but consider for content-driven row heights */
}

3. Call MasonIt.init() after your grid elements are in the DOM.

MasonIt.init('.my-masonry-grid', {
  masonDelay: 100, // Optional: delay in ms before first layout
  masonPollInterval: 0 // Optional: polling interval in ms, 0 = disabled
});

4. Or use the declarative attribute approach:

<div class="my-masonry-grid" data-mason-it>
  <div class="grid-item">Content 1</div>
  <div class="grid-item">Content 2</div>
  <!-- More grid items -->
</div>

<!-- With options -->
<div class="my-masonry-grid" data-mason-it="mason-delay:{500} mason-poll-interval:{2000}"></div>

5. API methods:

MasonIt.init(selector, [options])

  • selector: String CSS selector, Element, NodeList, or Array of elements.
  • options (Object, optional):
    • masonDelay (Number, default: 0): Milliseconds to wait before the initial layout.
    • masonPollInterval (Number, default: 0): Interval in ms to periodically check for content changes and refresh. 0 disables polling. MutationObserver is generally preferred.

MasonIt.refresh([selector])

  • Manually recalculates the layout for specified grid(s) or all initialized grids if no selector is given. Useful after asynchronous content changes that MutationObserver might not catch (e.g., image loads changing item dimensions significantly, or style changes affecting size).

MasonIt.destroy([selector])

  • Removes mason-it functionality and cleans up listeners for the specified grid(s) or all instances. Important for SPAs when components are unmounted.

MasonIt.debug(enable)

  • enable (Boolean): Toggles console debug messages. Can be helpful during setup.

MasonIt.version()

  • Returns the library version string (e.g., "1.0.1").

MasonIt.count()

  • Returns the number of active mason-it instances.

See Also:

The post Responsive Masonry Layouts with CSS Grid and Mason-it.js appeared first on CSS Script.


Discover more from RSS Feeds Cloud

Subscribe to get the latest posts sent to your email.

Discover more from RSS Feeds Cloud

Subscribe now to keep reading and get access to the full archive.

Continue reading