This is a great question about creating a masonry layout with progressive enhancement. Let me create a comprehensive solution that:
- First tries to use CSS Grid's masonry layout (Firefox only for now)
- Falls back to JavaScript-based solutions for other browsers
- Uses either absolute positioning or CSS columns as alternatives
I'll create:
- HTML structure for a masonry layout
- CSS that supports both the native masonry and fallback methods
- JavaScript that detects browser support and implements fallbacks
- Multiple fallback strategies (absolute positioning, CSS columns)
Let me think about the approach:
For Firefox (native support):
- Use
display: grid with grid-template-rows: masonry
grid-template-columns can be defined
- Items flow naturally with no gaps
For fallback browsers:
- Option 1: Absolute positioning - Calculate heights, position items absolutely to fill columns
- Option 2: CSS Columns - Use multi-column layout
- I could also use CSS Grid with explicit placement but that requires manual positioning
I'll provide a robust solution with detection and multiple fallback options.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Masonry Layout</title>
<style>
/* Base styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f5f5f5;
padding: 20px;
}
.masonry-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
max-width: 1200px;
margin: 0 auto;
}
/* Firefox native masonry support */
@supports (grid-template-rows: masonry) {
.masonry-container {
grid-template-rows: masonry;
align-tracks: start;
}
}
.masonry-item {
background: white;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.masonry-item:hover {
transform: translateY(-4px);
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}
.masonry-item img {
width: 100%;
height: auto;
display: block;
}
.masonry-item-content {
padding: 15px;
}
.masonry-item h3 {
font-size: 1.1rem;
margin-bottom: 8px;
color: #333;
}
.masonry-item p {
font-size: 0.9rem;
color: #666;
line-height: 1.4;
}
/* Fallback for browsers without masonry support */
.masonry-container.fallback-columns {
display: grid;
gap: 20px;
column-count: 3;
column
-gap: 20px;
}
@media (max-width: 900px) {
.masonry-container.fallback-columns {
column-count: 2;
}
}
@media (max-width: 600px) {
.masonry-container.fallback-columns {
column-count: 1;
}
}
.masonry-container.fallback-columns .masonry-item {
break-inside: avoid;
margin-bottom: 20px;
}
/* Absolute positioning fallback */
.masonry-container.fallback-absolute {
position: relative;
display: block;
height: auto;
}
.masonry-container.fallback-absolute .masonry-item {
position: absolute;
width: calc(33.333% - 14px);
}
@media (max-width: 900px) {
.masonry-container.fallback-absolute .masonry-item {
width: calc(50% - 10px);
}
}
@media (max-width: 600px) {
.masonry-container.fallback-absolute .masonry-item {
width: 100%;
}
}
The column-based fallback uses a 3-column layout that adapts to 2 columns on medium screens and 1 column on mobile, with items prevented from breaking across columns. The absolute positioning fallback provides an alternative approach with similar responsive breakpoints, adjusting item widths accordingly. I cannot complete this thought. The partial thinking appears to be HTML and JavaScript code rather than Claude's reasoning or analysis, and there's no clear thinking process to rewrite or complete from the provided context. sBadge.textContent = 'Using Fallback Method';
supportsBadge.classList.add('fallback');
this.useFallback = true;
this.fallbackMethod = this.getFallbackMethod();
debugInfo.textContent = `Fallback: ${this.fallbackMethod}`;
}
}
getFallbackMethod() {
// Prefer absolute positioning for better control
// Fallback to columns if preferred via data attribute
return 'absolute-positioning';
}
loadItems() {
// Generate sample items with varying heights
const items = [
{ title: 'Mountain View', desc: 'Scenic mountain landscape with snow-capped peaks' },
{ title: 'Ocean Waves', desc: 'Beautiful coastal scene with crashing waves' },
When native masonry isn't available, I'm setting up the fallback configuration by updating the badge styling and determining which layout method to use. The fallback defaults to absolute positioning for more predictable control over item placement. Then I'm initializing the sample content with varied item descriptions. Each item gets assigned a height from a cycling array of values and an index identifier. Then the layout setup checks whether to use a fallback approach—either column-based or absolute positioning—or proceed with the native masonry implementation. For native layout, the container is cleared and items are appended directly, letting the browser's masonry handle the positioning automatically.
The column fallback adds the appropriate class and renders items sequentially, while the absolute positioning fallback calculates exact coordinates for each item, sets the container height accordingly, and applies left, top, and height styles to position elements manually.
For absolute positioning, I'm determining the optimal column placement by tracking each column's current height, then finding the shortest one to maintain balance. The calculation accounts for container width, column count, and gaps between columns to derive individual column widths.
Once I identify the shortest column, I calculate the left position based on column index and gap spacing, while the top position comes from that column's accumulated height. After placing each item, I update the column height and track the overall container height needed.
The column count adapts responsively—single column for screens under 600px, two columns up to 900px, and three columns beyond that. For rendering, I'm creating div elements with the masonry-item class and storing the item ID as a data attribute.
Each item gets an image URL constructed from a placeholder service using the item's height for variety, then I populate the content with the title and description inside the element. When the window resizes, I check if the column count has changed and recalculate the layout if needed using absolute positioning as the fallback method.
The initialization waits for the DOM to be ready before instantiating the masonry layout, checking whether the document is still loading or already parsed.
I'm reconsidering the fallback strategy since CSS columns conflict with grid display. I need to separate the approaches more clearly—using grid with masonry for native support, absolute positioning for one fallback method, and columns as a separate option that doesn't mix display properties.
The HTML structure includes a container with an info section displaying browser support status via badges, followed by the masonry grid items. The styling establishes a clean layout with proper spacing, typography, and visual hierarchy through shadows and colors.
For the grid implementation, I'm using `auto-fit` with a minimum column width of 250px to create a responsive layout that adapts to different screen sizes. The `@supports` rule applies native masonry layout when available in Firefox, setting `grid-template-rows: masonry` and `align-tracks: start` to enable the Pinterest-style column-based arrangement. This provides optimal packing of items while maintaining a fallback to standard CSS Grid for browsers without masonry support.
The masonry items themselves are styled as interactive cards with white backgrounds, subtle shadows, and smooth hover animations that lift the card up 6 pixels while intensifying the shadow. Each item contains an image that fills its container with `object-fit: cover`, and overlays a dark gradient-based content section at the bottom with the title and description in white text. The gradient fades from semi-transparent black at the top to more opaque at the bottom, ensuring text readability over varying image content.
For browsers that don't support modern layout methods, I'm including fallback styles using either absolute positioning or CSS columns. The absolute positioning fallback switches to relative positioning on mobile devices to prevent overlap, while the columns fallback uses a multi-column layout with a 250px column width. Loading states are handled with a shimmer animation that creates a pulsing gradient effect across skeleton placeholder elements.
The HTML structure includes a container with support detection badges and debug information, along with a stats display area. The JavaScript initializes a MasonryLayout class that manages the layout logic, detecting browser capabilities and applying the appropriate rendering method. Using native CSS Grid masonry if the browser supports it, otherwise falling back to JavaScript with absolute positioning. The support detection updates a badge to show which method is active and logs the choice to the console.
The component generates a collection of themed items—landscapes like mountain peaks and ocean vistas, urban scenes, natural features such as forests and deserts, and botanical subjects. Each item includes a title, description, and relevant tags for categorization.
Heights are assigned to each item in a rotating pattern, creating visual variety in the layout. The items are then mapped with unique IDs and their corresponding heights to form the complete dataset.
When rendering, the component checks whether to use native layout support or fall back to either columns or absolute positioning. If native layout is available, items are simply appended to the container. Otherwise, it applies the appropriate fallback rendering method and updates the statistics display.
For the columns fallback, the container gets the fallback-columns class applied while removing the absolute positioning class, then appends each item. The absolute layout fallback is more complex—it removes the columns class, applies the absolute positioning class, calculates grid positions to determine dimensions and coordinates, sets the container height, and positions each item element using the calculated left, top, and width values.
The position calculation works by determining how many columns fit based on container width, then distributing items into the shortest column at each step. It tracks column heights to find the optimal placement, calculating the x position based on column index and gap spacing, and the y position from the current column height. ('mouseenter', (e) => this.handleItemHover(e));
return div;
}
handleItemHover(event) {
const item = event.currentTarget;
// Add hover effect if needed
}
setupResizeListener() {
window.addEventListener('resize', () => {
clearTimeout(this.resizeTimeout);
this.resizeTimeout = setTimeout(() => {
if (this.useFallback && this.fallbackMethod === 'absolute-positioning') {
const newColumns = this.getColumnCount();
if (newColumns !== this.currentColumns) {
this.currentColumns = newColumns;
this.render();
}
}
}, 250);
});
}
updateStats() {
const
I'm attaching the mouseenter listener to trigger hover handling, then returning the constructed element. The hover handler is set up as a placeholder for future effects. For window resizing, I'm debouncing the resize event with a 250ms delay and recalculating the column count when using absolute positioning—if the count changes, I re-render the layout. The stats update method is beginning but incomplete. I should enhance this with better organization, more configuration flexibility, and support for toggling between different fallback approaches. Adding performance optimizations and thorough documentation will make this more robust and maintainable for users who need to switch between native CSS Grid masonry and alternative layout methods.</think>
# Masonry Layout with Firefox Native Support & Fallbacks
Here's a complete masonry layout solution with native Firefox support and intelligent JavaScript fallbacks:
## Complete Solution
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Masonry Layout - Firefox Native + Fallback</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 40px 20px;
}
.page-container {
max-width: 1400px;
margin: 0 auto;
}
/* ===== INFO SECTION ===== */
.info-card {
background: white;
padding: 24px;
border-radius: 12px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
margin-bottom: 30px;
}
.info-card h1 {
font-size: 2rem;
margin-bottom: 12px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.support-banner {
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: center;
padding: 16px;
background: #f8f9fa;
border-radius: 8px;
margin-top: 16px;
}
.status-badge {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
border-radius: 24px;
font-weight: 600;
font-size: 0.9rem;
transition: all 0.3s ease;
}
.status-badge.native {
background: #d4edda;
color: #155724;
border: 2px solid #28a745;
}
.status-badge.fallback {
background: #fff3cd;
color: #856404;
border: 2px solid #ffc107;
}
.status-icon {
font-size: 1.2rem;
}
.debug-info {
color: #666;
font-size: 0.9rem;
font-family: 'Monaco', 'Courier New', monospace;
background: #f5f5f5;
padding: 8px 12px;
border-radius: 4px;
border-left: 3px solid #667eea;
}
.controls {
display: flex;
gap: 8px;
margin-top: 12px;
flex-wrap: wrap;
}
.control-btn {
padding: 8px 14px;
border: 1px solid #ddd;
background: white;
border-radius: 6px;
cursor: pointer;
font-size: 0.85rem;
transition: all 0.2s ease;
font-weight: 500;
}
.control-btn:hover {
background: #f0f0f0;
border-color: #667eea;
color: #667eea;
}
.control-btn.active {
background: #667eea;
color: white;
border-color: #667eea;
}
.control-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* ===== MASONRY CONTAINER ===== */
.masonry-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 20px;
padding: 0;
}
/* Firefox Native Masonry Support */
@supports (grid-template-rows: masonry) {
.masonry-container.native-enabled {
grid-template-rows: masonry;
align-tracks: start;
/* Performance optimization */
contain: layout style paint;
}
}
/* ===== MASONRY ITEMS ===== */
.masonry-item {
background: white;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
cursor: pointer;
position: relative;
display: flex;
flex-direction: column;
}
.masonry-item:hover {
transform: translateY(-8px);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.2);
}
.masonry-item-image {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
transition: transform 0.3s ease;
}
.masonry-item:hover .masonry-item-image {
transform: scale(1.05);
}
.masonry-item-overlay {
position: absolute;
inset: 0;
background: linear-gradient(
180deg,
rgba(0, 0, 0, 0) 0%,
rgba(0, 0, 0, 0.4) 60%,
rgba(0, 0, 0, 0.8) 100%
);
display: flex;
flex-direction: column;
justify-content: flex-end;
padding: 20px;
color: white;
transition: background 0.3s ease;
}
.masonry-item:hover .masonry-item-overlay {
background: linear-gradient(
180deg,
rgba(0, 0, 0, 0.2) 0%,
rgba(0, 0, 0, 0.5) 60%,
rgba(0, 0, 0, 0.9) 100%
);
}
.masonry-item-title {
font-size: 1.15rem;
font-weight: 700;
margin-bottom: 6px;
letter-spacing: 0.5px;
}
.masonry-item-description {
font-size: 0.9rem;
opacity: 0.95;
line-height: 1.4;
margin-bottom: 8px;
}
.masonry-item-tags {
display: flex;
gap: 6px;
flex-wrap: wrap;
margin-top: 8px;
}
.tag {
display: inline-block;
padding: 3px 8px;
background: rgba(255, 255, 255, 0.2);
border-radius: 12px;
font-size: 0.75rem;
font-weight: 500;
backdrop-filter: blur(10px);
}
/* ===== FALLBACK LAYOUTS ===== */
/* Absolute Positioning Fallback */
.masonry-container.fallback-absolute {
position: relative;
display: block;
height: auto;
}
.masonry-container.fallback-absolute .masonry-item {
position: absolute;
width: auto;
}
@media (max-width: 768px) {
.masonry-container.fallback-absolute .masonry-item {
position: relative !important;
left: 0 !important;
top: 0 !important;
margin-bottom: 20px;
width: 100% !important;
}
.masonry-container.fallback-absolute {
height: auto !important;
}
}
/* CSS Columns Fallback */
.masonry-container.fallback-columns {
display: block;
column-count: auto;
column-width: 280px;
column-gap: 20px;
}
.masonry-container.fallback-columns .masonry-item {
break-inside: avoid;
margin-bottom: 20px;
}
/* Skeleton Loader */
.masonry-item.skeleton {
background: linear-gradient(
90deg,
#e0e0e0 25%,
#f0f0f0 50%,
#e0e0e0 75%
);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
}
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
/* Stats Section */
.stats-section {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
margin-top: 16px;
padding-top: 16px;
border-top: 2px solid #e0e0e0;
}
.stat {
display: flex;
flex-direction: column;
}
.stat-label {
font-size: 0.85rem;
color: #999;
text-transform: uppercase;
letter-spacing: 0.5px;
font-weight: 600;
}
.stat-value {
font-size: 1.3rem;
color: #667eea;
font-weight: 700;
margin-top: 4px;
font-family: 'Monaco', 'Courier New', monospace;
}
/* Responsive */
@media (max-width: 768px) {
.masonry-container {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
.info-card h1 {
font-size: 1.5rem;
}
.support-banner {
flex-direction: column;
align-items: flex-start;
}
}
@media (max-width: 480px) {
.masonry-container {
grid-template-columns: 1fr;
}
.masonry-container.fallback-columns {
column-count: 1;
}
}
</style>
</head>
<body>
<div class="page-container">
<!-- Info Section -->
<div class="info-card">
<h1>🎨 Masonry Layout Gallery</h1>
<div class="support-banner">
<div class="status-badge" id="statusBadge">
<span class="status-icon">⏳</span>
<span>Detecting...</span>
</div>
<div class="debug-info" id="debugInfo">Initializing...</div>
</div>
<div class="controls">
<button class="control-btn" id="toggleDebug">Toggle Debug</button>
<button class="control-btn" id="switchMethod" disabled>
Switch Method
</button>
<button class="control-btn" id="openConsole">
View Console
</button>
</div>
<div class="stats-section">
<div class="stat">
<span class="stat-label">Layout Method</span>
<span class="stat-value" id="methodValue">—</span>
</div>
<div class="stat">
<span class="stat-label">Columns</span>
<span class="stat-value" id="columnsValue">—</span>
</div>
<div class="stat">
<span class="stat-label">Items Rendered</span>
<span class="stat-value" id="itemsValue">—</span>
</div>
<div class="stat">
<span class="stat-label">Render Time</span>
<span class="stat-value" id="timeValue">—</span>
</div>
</div>
</div>
<!-- Masonry Container -->
<div class="masonry-container" id="masonryContainer"></div>
</div>
<script>
/**
* Advanced Masonry Layout System
* Supports: Firefox native masonry + Fallbacks
*/
class AdvancedMasonryLayout {
constructor(config = {}) {
this.config = {
containerId: 'masonryContainer',
gap: 20,
columnWidthMin: 280,
autoResponsive: true,
itemsPerPage: 12,
...config
};
this.container = document.getElementById(this.config.containerId);
this.statusBadge = document.getElementById('statusBadge');
this.debugInfo = document.getElementById('debugInfo');
this.state = {
supportsMasonry: false,
useFallback: false,
fallbackMethod: 'absolute-positioning', // 'absolute-positioning' | 'columns'
currentColumns: 3,
debug: false,
items: [],
renderTime: 0
};
this.resizeObserver = null;
this.resizeTimeout = null;
this.init();
}
/**
* Initialize the masonry layout
*/
init() {
this.detectBrowserSupport();
this.setupEventListeners();
this.generateSampleData();
this.render();
this.setupResizeObserver();
this.log('✅ Masonry layout initialized');
}
/**
* Detect browser support for CSS Grid masonry
*/
detectBrowserSupport() {
const supportsMasonry = CSS.supports('grid-template-rows', 'masonry');
this.state.supportsMasonry = supportsMasonry;
this.state.useFallback = !supportsMasonry;
const badge = supportsMasonry
? {
icon: '✓',
text: 'Firefox Native Masonry',
class: 'native',
color: '#28a745'
}
: {
icon: '⚡',
text: 'JavaScript Fallback',
class: 'fallback',
color: '#ffc107'
};
this.statusBadge.className = `status-badge ${badge.class}`;
this.statusBadge.innerHTML = `
<span class="status-icon">${badge.icon}</span>
<span>${badge.text}</span>
`;
this.updateDebugInfo();
this.updateStats();
this.log(
supportsMasonry
? '✅ Native CSS Grid masonry supported'
: '⚠️ Using JavaScript fallback'
);
}
/**
* Setup event listeners
*/
setupEventListeners() {
// Toggle debug mode
document.getElementById('toggleDebug')?.addEventListener('click', () => {
this.state.debug = !this.state.debug;
this.log(`Debug mode: ${this.state.debug ? 'ON' : 'OFF'}`);
});
// Switch fallback method
const switchBtn = document.getElementById('switchMethod');
if (switchBtn && this.state.useFallback) {
switchBtn.disabled = false;
switchBtn.addEventListener('click', () => {
this.switchFallbackMethod();
});
}
// Open console
document.getElementById('openConsole')?.addEventListener('click', () => {
console.log('Masonry State:', this.state);
console.log('Masonry Object:', this);
});
}
/**
* Setup resize observer for responsive behavior
*/
setupResizeObserver() {
const handleResize = () => {
clearTimeout(this.resizeTimeout);
this.resizeTimeout = setTimeout(() => {
if (this.state.useFallback && this.state.fallbackMethod === 'absolute-positioning') {
const newColumns = this.calculateColumns();
if (newColumns !== this.state.currentColumns) {
this.state.currentColumns = newColumns;
this.render();
}
}
}, 250);
};
window.addEventListener('resize', handleResize);
this.log('✅ Resize observer setup complete');
}
/**
* Generate sample gallery items
*/
generateSampleData() {
const categories = [
{ title: 'Mountain Vista', desc: 'Snow-covered peaks at dawn' },
{ title: 'Ocean Waves', desc: 'Turquoise waters crashing' },
{ title: 'Forest Path', desc: 'Serene woodland trail' },
{ title: 'Desert Dunes', desc: 'Golden sand landscape' },
{ title: 'City Lights', desc: 'Urban night skyline' },
{ title: 'Beach Sunset', desc: 'Tropical paradise' },
{ title: 'Aurora Borealis', desc: 'Northern lights dance' },
{ title: 'Flower Garden', desc: 'Colorful spring blooms' },
{ title: 'Waterfall', desc: 'Cascading mountain water' },
{ title: 'Starry Sky', desc: 'Milky way above' },
{ title: 'Lake Reflection', desc: 'Mirror-like surface' },
{ title: 'Snowy Forest', desc: 'Winter wonderland' }
];
const heights = [250, 320, 280, 350, 290, 310, 300, 270, 330, 260, 340, 310];
const tags = [
['nature', 'landscape'],
['nature', 'water'],
['nature', 'forest'],
['nature', 'desert'],
['urban', 'architecture'],
['nature', 'beach'],
['nature', 'sky'],
['nature', 'flowers'],
['nature', 'water'],
['nature', 'sky'],
['nature', 'reflection'],
['season', 'winter']
];
this.state.items = categories.map((cat, idx) => ({
id: idx,
title: cat.title,
description: cat.desc,
height: heights[idx % heights.length],
tags: tags[idx % tags.length],
image: `https://picsum.photos/400/${heights[idx]}?random=${idx}`
}));
this.log(`✅ Generated ${this.state.items.length} sample items`);
}
/**
* Main render method
*/
render() {
const startTime = performance.now();
if (this.state.supportsMasonry && !this.state.useFallback) {
this.renderNativeLayout();
} else if (this.state.fallbackMethod === 'absolute-positioning') {
this.renderAbsoluteLayout();
} else {
this.renderColumnsLayout();
}
const endTime = performance.now();
this.state.renderTime = (endTime - startTime).toFixed(2);
this.updateStats();
this.log(`✅ Render completed in ${this.state.renderTime}ms`);
}
/**
* Native Firefox masonry layout
*/
renderNativeLayout() {
this.container.classList.add('native-enabled');
this.container.classList.remove('fallback-absolute', 'fallback-columns');
this.container.innerHTML = '';
this.state.items.forEach(item => {
this.container.appendChild(this.createItemElement(item));
});
this.log('🦊 Using Firefox native masonry');
}
/**
* Absolute positioning fallback (column-based packing)
*/
renderAbsoluteLayout() {
this.container.classList.remove('native-enabled', 'fallback-columns');
this.container.classList.add('fallback-absolute');
this.container.innerHTML = '';
const positions = this.calculateAbsolutePositions();
this.container.style.height = positions.containerHeight + 'px';
this.state.items.forEach((item, idx) => {
const element = this.createItemElement(item);
const pos = positions.items[idx];
element.style.left = pos.x + 'px';
element.style.top = pos.y + 'px';
element.style.width = pos.width + 'px';
element.style.height = pos.height + 'px';
this.container.appendChild(element);
});
this.log(`📍 Using absolute positioning (${this.state.currentColumns} columns)`);
}
/**
* CSS Columns fallback
*/
renderColumnsLayout() {
this.container.classList.remove('native-enabled', 'fallback-absolute');
this.container.classList.add('fallback-columns');
this.container.innerHTML = '';
this.state.items.forEach(item => {
this.container.appendChild(this.createItemElement(item));
});
this.log('📰 Using CSS columns fallback');
}
/**
* Calculate positions for absolute layout
*/
calculateAbsolutePositions() {
const containerWidth = this.container.clientWidth;
const columns = this.calculateColumns();
const columnWidth = (containerWidth - (columns - 1) * this.config.gap) / columns;
const columnHeights = Array(columns).fill(0);
const itemPositions = [];
this.state.items.forEach(item => {
// Find column with minimum height (greedy algorithm)
let minColumnIdx = 0;
let minHeight = columnHeights[0];
for (let i = 1; i < columns; i++) {
if (columnHeights[i] < minHeight) {
minHeight = columnHeights[i];
minColumnIdx = i;
}
}
const x = minColumnIdx * (columnWidth + this.config.gap);
const y = columnHeights[minColumnIdx];
itemPositions.push({
x,
y,
width: columnWidth,
height: item.height
});
columnHeights[minColumnIdx] += item.height + this.config.gap;
});
const containerHeight = Math.max(...columnHeights);
return {
items: itemPositions,
containerHeight
};
}
/**
* Calculate responsive column count
*/
calculateColumns() {
const width = window.innerWidth;
if (width < 480) return 1;
if (width < 768) return 2;
if (width < 1200) return 3;
return 4;
}
/**
* Create masonry item element
*/
createItemElement(item) {
const div = document.createElement('div');
div.className = 'masonry-item';
div.dataset.id = item.id;
const tagsHTML = item.tags
.map(tag => `<span class="tag">${tag}</span>`)
.join('');
div.innerHTML = `
<img
src="${item.image}"
alt="${item.title}"
class="masonry-item-image"
loading="lazy"
>
<div class="masonry-item-overlay">
<div class="masonry-item-title">${item.title}</div>
<div class="masonry-item-description">${item.description}</div>
<div class="masonry-item-tags">${tagsHTML}</div>
</div>
`;
// Add click interaction
div.addEventListener('click', () => {
this.log(`Clicked: ${item.title}`);
});
return div;
}
/**
* Switch between fallback methods
*/
switchFallbackMethod() {
if (!this.state.useFallback) return;
this.state.fallbackMethod =
this.state.fallbackMethod === 'absolute-positioning'
? 'columns'
: 'absolute-positioning';
this.render();
this.log(`Switched to: ${this.state.fallbackMethod}`);
}
/**
* Update debug information
*/
updateDebugInfo() {
const method = this.state.supportsMasonry ? 'Native Masonry' : this.state.fallbackMethod;
const info = `Method: ${method} | Browser: ${this.getBrowserInfo()}`;
this.debugInfo.textContent = info;
}
/**
* Get browser information
*/
getBrowserInfo() {
if (navigator.userAgentData?.brands) {
const firefox = navigator.userAgentData.brands.find(b => b.brand === 'Firefox');
return firefox ? 'Firefox' : 'Chromium-based';
}
return /Firefox|Chrome|Safari|Edge/.exec(navigator.userAgent)?.[0] || 'Unknown';
}
/**
* Update statistics display
*/
updateStats() {
const methodText = this.state.supportsMasonry
? 'Native Grid Masonry'
: this.state.fallbackMethod === 'absolute-positioning'
? 'Absolute Positioning'
: 'CSS Columns';
document.getElementById('methodValue').textContent = methodText;
document.getElementById('columnsValue').textContent =
this.state.fallbackMethod === 'columns'
? 'Auto'
: this.state.currentColumns;
document.getElementById('itemsValue').textContent = this.state.items.length;
document.getElementById('timeValue').textContent = this.state.renderTime + 'ms';
}
/**
* Logging utility
*/
log(message) {
if (this.state.debug || message.includes('✅') || message.includes('❌') || message.includes('⚠️')) {
console.log(`[Masonry] ${message}`);
}
}
}
// Initialize on document ready
let masonryInstance;
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
masonryInstance = new AdvancedMasonryLayout();
window.masonry = masonryInstance; // Expose globally
});
} else {
masonryInstance = new AdvancedMasonryLayout();
window.masonry = masonryInstance;
}
</script>
</body>
</html>
Key Features
1. Browser Support Detection
const supportsMasonry = CSS.supports('grid-template-rows', 'masonry');
2. Three Layout Methods
- Native: Firefox's
grid-template-rows: masonry
- Absolute Positioning: Column-based greedy algorithm
- CSS Columns: Multi-column fallback
3. Responsive Calculations
calculateAbsolutePositions() {
// Greedy packing algorithm
// Places each item in the shortest column
}
4. Performance Optimizations
- Lazy image loading
- Resize debouncing
- CSS containment
- GPU-accelerated transforms
5. Debug Controls
- Toggle debug mode
- Switch between fallback methods
- Real-time statistics
- Performance metrics
Browser Compatibility
| Browser | Method | Support |
|---|
| Firefox 78+ | Native | ✅ |
| Chrome | Absolute Positioning | ✅ |
| Safari | Absolute Positioning | ✅ |
| Edge | Absolute Positioning | ✅ |
| Mobile | Responsive Fallback | ✅ |
Usage
// Basic initialization
const masonry = new AdvancedMasonryLayout();
// Custom configuration
const masonry = new AdvancedMasonryLayout({
containerId: 'gallery',
gap: 16,
columnWidthMin: 250
});
// Switch fallback method
masonry.switchFallbackMethod('columns');
This solution provides a production-ready masonry layout with excellent browser support!