Explain Codes LogoExplain Codes Logo

Css-only masonry layout

html
responsive-design
css-grid
browser-compatibility
Nikita BarsukovbyNikita Barsukov·Aug 25, 2024
TLDR

Here's a quick setup for a CSS masonry layout leveraging CSS columns:

.masonry { /* Magic number 3: Three's a crowd, column-count */ column-count: 3; /* Giving columns a little personal space. No hugging today. */ column-gap: 16px; } .item { /* Telling items not to behave like gymnasts: No splitting */ break-inside: avoid-column; /* Extra belly space for each item */ margin-bottom: 16px; }
<div class="masonry"> <!-- Items here --> <div class="item">1</div> <div class="item">2</div> <div class="item">3</div> </div>

Here, column-count in the container and break-inside on items maintain integrity and prevent splitting. Modify column and margin sizes on demand.

In-depth analysis and practical examples

CSS Grid Level 3: A new hope for masonry

The CSS Grid Level 3 introduces masonry with grid-template-rows: masonry;, providing more simplified support for masonry layouts.

.grid { display: grid; /* Get you a grid that can do both: Resize and fill */ grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); /* When Row meets Masonry: A romantic comedy */ grid-template-rows: masonry; }

This snippet distributes your items in to columns of minimum 250px width.

Flexbox vs CSS Grid: Dawn of masonry

Considering Flexbox for a masonry-esque layout? flex-direction: column; can help, but CSS Grid outshines with a more versatile two-dimensional solution, allowing items to stride across columns and rows.

Crystal ball: Finetuning CSS Grid masonry

Knowing the dimensions? Perfect! Use grid-auto-rows, grid-gap, and grid-template-columns to shape the structure while catering content of different sizes.

Playing it simple: CSS Columns for masonry

Combine display: inline-block, width: 100% on the item, column-count and column-gap to formulate a clean, column-based layout.

Spacing: The final frontier

padding, margin and box-sizing: border-box; tango together for managing spacing within masonry layout ensuring precise calculation.

Responsive design: One size doesn't fit all

Enrich responsive masonry layout by tweaking column-count and item widths via media queries, ensuring adaption across devices.

Different heights for distinctive layouts

Add aesthetic appeal to your layout by linking different classes with varying heights to masonry items.

A picture's worth a thousand pixels: Image sizing within grids

Embed flexible sizing with <img> tags in grid items to maintain a flawless layout despite image dimensions.

Browser compatibility: Frenemy of the state

Always cross-check the browser compatibility especially for even newer CSS properties, such as CSS Grid Level 3, for a user-friendly layout.

Pure CSS masonry fallback: JavaScript amenities

If CSS seems too limiting, tools like Masonry.js come to the rescue. They provide enhanced control for absolute positioning in complex layouts.