Explore Create a responsive Beercss grid system with a Pinterest-style masonry layout using CSS… Save Share Download ▾ ReportCreate a responsive Beercss grid system with a Pinterest-style masonry layout using CSS Grid with row-span calculations in JS. Provide a fallback for browsers that don't support native masonry.
AssistantCopy response Copy first prompt Copy first response
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider anthropic
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language —
Added to archive Nov 21, 2026
ID 01m7y9acwv5x895qqqj4t9me7ySource & license Imported from Frontier Reasoning Traces (source ). Imported records earn no Research Points.
Upstream record: train-0.parquet:1908
SultanR/frontier-reasoning-traces-sft, revision 0e6b23142b95f5fe.
License: Apache-2.0
Dataset releases Not yet included in a published release.
This is a great request for a comprehensive front-end solution. Let me break down what's needed:
A responsive Beercss grid system (Beercss is a minimal CSS framework)
Pinterest-style masonry layout using CSS Grid
Row-span calculations in JavaScript
Fallback for browsers that don't support native masonry
Should be responsive
Let me create a complete solution with:
HTML structure
CSS Grid with dynamic row-span calculation
JavaScript for calculating row spans based on image dimensions
CSS fallback for unsupported browsers
Responsive design
Examples with different image sizes
I'll make this comprehensive with proper explanations and multiple fallback options.
Beercss Grid System with Pinterest-Style Masonry Layout
Here's a complete responsive masonry solution with CSS Grid and JavaScript calculations:
1. HTML Structure
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Beercss Masonry Grid</title>
<link rel="stylesheet" href="beercss.css">
<link rel="stylesheet" href="masonry.css">
</head>
<body>
<div class="container">
<h1>Pinterest-Style Masonry Layout</h1>
<!-- Masonry Grid -->
<div class="masonry-grid" id="masonryGrid">
<figure class="masonry-item">
<img src="https://picsum.photos/300/400?random=1" alt="Gallery item 1">
<figcaption>Image 1</figcaption>
</figure>
<figure class="masonry-item">
<img src="https://picsum.photos/300/500?random=2" alt="Gallery item 2">
<figcaption>Image 2</figcaption>
</figure>
<figure class="masonry-item">
<img src="https://picsum.photos/300/350?random=3" alt="Gallery item 3">
<figcaption>Image 3</figcaption>
</figure>
<figure class="masonry-item">
<img src="https://picsum.photos/300/450?random=4" alt="Gallery item 4">
<figcaption>Image 4</figcaption>
</figure>
<figure class="masonry-item">
<img src="https://picsum.photos/300/380?random=5" alt="Gallery item 5">
<figcaption>Image 5</figcaption>
</figure>
<figure class="masonry-item">
<img src="https://picsum.photos/300/420?random=6" alt="Gallery item 6">
<figcaption>Image 6</figcaption>
</figure>
<figure class="masonry-item">
<img src="https://picsum.photos/300/360?random=7" alt="Gallery item 7">
<figcaption>Image 7</figcaption>
</figure>
<figure class="masonry-item">
<img src="https://picsum.photos/300/480?random=8" alt="Gallery item 8">
<figcaption>Image 8</figcaption>
</figure>
</div>
</div>
<script src="masonry.js"></script>
</body>
</html>
2. Beercss-Based CSS Grid
masonry.css :
3. JavaScript Row-Span Calculator
masonry.js :
4. Advanced Features Extension
masonry-advanced.js (Optional advanced features):
5. Complete Beercss Framework (Minimal)
beercss.css :
css Copy code
/* Beercss - Minimal CSS Framework */
:root {
--font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
--font-size: 1rem;
--line-height: 1.6;
--color-primary: #3498db;
--color-success: #2ecc71;
--color-danger: #e74c3c;
--color-warning: #f39c12;
--color-dark: #2c3e50;
--color-light: #ecf0f1;
--border-radius: 0.25rem;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
font-family: var(--font-family);
font-size: var(--font-size);
line-height: var(--line-height);
color: var(--color-dark);
background: white;
}
/* Typography */
h1, h2, h3, h4, h5, h6 {
font-weight: 600;
margin-bottom: 1rem;
}
h1 { font-size: 2.5rem; }
h2 { font-size: 2rem; }
h3 { font-size: 1.75rem; }
h4 { font-size: 1.5rem; }
h5 { font-size: 1.25rem; }
h6 { font-size: 1rem; }
p { margin-bottom: 1rem; }
a {
color: var(--color-primary);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* Buttons */
button, .button {
display: inline-block;
padding: 0.5rem 1rem;
border: 1px solid var(--color-primary);
border-radius: var(--border-radius);
background: var(--color-primary);
color: white;
cursor: pointer;
font-size: 1rem;
transition: all 0.3s;
}
button:hover {
opacity: 0.9;
transform: translateY(-2px);
}
/* Forms */
input, textarea, select {
display: block;
width: 100%;
padding: 0.5rem;
margin-bottom: 1rem;
border: 1px solid var(--color-light);
border-radius: var(--border-radius);
font-family: inherit;
font-size: inherit;
}
input:focus, textarea:focus, select:focus {
outline: none;
border-color: var(--color-primary);
box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}
/* Tables */
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 2rem;
}
thead {
background: var(--color-light);
}
th, td {
padding: 0.75rem;
text-align: left;
border-bottom: 1px solid var(--color-light);
}
/* Utilities */
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 1rem;
}
.text-center { text-align: center; }
.text-right { text-align: right; }
.text-left { text-align: left; }
.m-0 { margin: 0; }
.p-0 { padding: 0; }
.d-flex {
display: flex;
}
.gap-1 { gap: 0.5rem; }
.gap-2 { gap: 1rem; }
.flex-item { flex: 1; }
.opacity-50 { opacity: 0.5; }
.opacity-75 { opacity: 0.75; }
6. Usage Example with Lazy Loading
html Copy code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="beercss.css">
<link rel="stylesheet" href="masonry.css">
<style>
.masonry-item img[data-src] {
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 200% 100%;
animation: shimmer 2s infinite;
}
</style>
</head>
<body>
<div class="container">
<h1>Advanced Masonry Gallery</h1>
<div class="masonry-grid" id="masonryGrid">
<!-- Items will be generated here -->
</div>
</div>
<script src="masonry.js"></script>
<script src="masonry-advanced.js"></script>
</body>
</html>
Features Summary
✅ CSS Grid Native Masonry - Uses native CSS Grid masonry when available
✅ JavaScript Fallback - Calculates row spans for older browsers
✅ Responsive Design - Adapts to 5 breakpoints (mobile to 4K)
✅ Dynamic Row Calculation - Based on image aspect ratios
✅ Infinite Scroll - Load more items on demand
✅ Lazy Loading - Images load on scroll
✅ Filter/Search - Categorize and filter items
✅ ResizeObserver - Recalculates on window resize
✅ MutationObserver - Detects dynamically added items
✅ Lightbox - Click to preview full-size images
✅ Beercss Compatible - Minimal framework integration
This provides a complete, production-ready masonry solution! 🎉
Show full message · 1,170 lines /* ===================================
Beercss Custom Masonry Extensions
=================================== */
:root {
/* Grid Configuration */
--grid-columns: 4;
--grid-gap: 1rem;
--grid-auto-rows: 200px;
--grid-min-width: 600px;
/* Colors */
--primary-color: #3498db;
--secondary-color: #2c3e50;
--light-bg: #ecf0f1;
--border-color: #bdc3c7;
/* Beercss Variables */
--font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--font-size: 1rem;
--line-height: 1.6;
--border-radius: 0.5rem;
--transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
/* ===== Base Styles ===== */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: var(--font-family);
font-size: var(--font-size);
line-height: var(--line-height);
color: var(--secondary-color);
background-color: #f8f9fa;
}
.container {
max-width: 1400px;
margin: 0 auto;
padding: 2rem 1rem;
}
h1 {
text-align: center;
margin-bottom: 2rem;
font-size: 2.5rem;
font-weight: 600;
color: var(--secondary-color);
}
/* ===== Masonry Grid - CSS Grid Version ===== */
.masonry-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-auto-rows: var(--grid-auto-rows);
grid-gap: var(--grid-gap);
grid-auto-flow: dense;
/* Enable native masonry if supported */
grid-template-columns: masonry;
}
/* Fallback for browsers without masonry support */
@supports not (grid-template-columns: masonry) {
.masonry-grid {
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-auto-rows: auto;
grid-auto-flow: row;
}
}
/* ===== Masonry Items ===== */
.masonry-item {
position: relative;
overflow: hidden;
border-radius: var(--border-radius);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
cursor: pointer;
transition: var(--transition);
background: white;
display: flex;
flex-direction: column;
}
.masonry-item:hover {
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
transform: translateY(-4px);
}
.masonry-item img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
transition: var(--transition);
}
.masonry-item:hover img {
transform: scale(1.05);
}
/* ===== Image Aspect Ratios ===== */
/* Tall items (span 2 rows) */
.masonry-item[data-rows="2"] {
grid-row: span 2;
}
/* Extra tall items (span 3 rows) */
.masonry-item[data-rows="3"] {
grid-row: span 3;
}
/* Wide items (span 2 columns) */
.masonry-item[data-cols="2"] {
grid-column: span 2;
}
/* ===== Figcaption Overlay ===== */
figcaption {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
color: white;
padding: 1.5rem 1rem 1rem;
transform: translateY(100%);
transition: var(--transition);
font-size: 0.95rem;
font-weight: 500;
}
.masonry-item:hover figcaption {
transform: translateY(0);
}
/* ===== Responsive Design ===== */
/* Large screens (1200px+) */
@media (min-width: 1200px) {
:root {
--grid-columns: 5;
--grid-gap: 1.5rem;
--grid-auto-rows: 220px;
}
.masonry-grid {
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
}
}
/* Medium screens (768px - 1199px) */
@media (max-width: 1199px) and (min-width: 768px) {
:root {
--grid-columns: 3;
--grid-gap: 1rem;
--grid-auto-rows: 200px;
}
.masonry-grid {
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
}
/* Small screens (576px - 767px) */
@media (max-width: 767px) {
:root {
--grid-columns: 2;
--grid-gap: 0.75rem;
--grid-auto-rows: 180px;
}
.masonry-grid {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}
h1 {
font-size: 1.75rem;
}
.masonry-item[data-cols="2"] {
grid-column: span 1;
}
}
/* Extra small screens (< 576px) */
@media (max-width: 575px) {
:root {
--grid-columns: 1;
--grid-gap: 0.5rem;
--grid-auto-rows: 300px;
}
.masonry-grid {
grid-template-columns: 1fr;
}
.masonry-item[data-rows="2"],
.masonry-item[data-rows="3"],
.masonry-item[data-cols="2"] {
grid-row: auto;
grid-column: auto;
}
h1 {
font-size: 1.5rem;
}
}
/* ===== Loading & Error States ===== */
.masonry-item.loading {
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 200% 100%;
animation: shimmer 2s infinite;
}
@keyframes shimmer {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
.masonry-item img.error {
display: none;
}
.masonry-item.error::after {
content: "Failed to load";
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background: var(--light-bg);
color: #999;
font-size: 0.9rem;
}
/* ===== Beercss Typography ===== */
h1, h2, h3, h4, h5, h6 {
font-weight: 600;
line-height: 1.2;
margin-bottom: 1rem;
}
/* ===== Utility Classes ===== */
.text-center {
text-align: center;
}
.mt-1 { margin-top: 0.5rem; }
.mt-2 { margin-top: 1rem; }
.mt-3 { margin-top: 1.5rem; }
.mt-4 { margin-top: 2rem; }
.mb-1 { margin-bottom: 0.5rem; }
.mb-2 { margin-bottom: 1rem; }
.mb-3 { margin-bottom: 1.5rem; }
.mb-4 { margin-bottom: 2rem; }
.p-1 { padding: 0.5rem; }
.p-2 { padding: 1rem; }
.p-3 { padding: 1.5rem; }
.p-4 { padding: 2rem; }
/**
* Masonry Grid - Advanced Layout Engine
* Supports CSS Grid native masonry with JavaScript fallback
*/
class MasonryGrid {
constructor(options = {}) {
this.grid = document.getElementById(options.gridId || 'masonryGrid');
this.minRowHeight = options.minRowHeight || 200;
this.gap = options.gap || 16;
this.columnWidth = options.columnWidth || 250;
this.maxRatio = options.maxRatio || 2;
this.supportsNativeMasonry = this.checkNativeMasonrySupport();
this.resizeObserver = null;
this.mutationObserver = null;
this.init();
}
/**
* Check if browser supports native CSS Grid masonry
*/
checkNativeMasonrySupport() {
if (!CSS || !CSS.supports) return false;
return CSS.supports('grid-template-columns', 'masonry');
}
/**
* Initialize the masonry grid
*/
init() {
if (!this.grid) {
console.error('Masonry grid element not found');
return;
}
this.setupGrid();
this.processItems();
this.attachEventListeners();
this.setupObservers();
}
/**
* Setup grid container with appropriate calculations
*/
setupGrid() {
if (this.supportsNativeMasonry) {
console.log('Using native CSS Grid masonry');
this.grid.classList.add('masonry-native');
} else {
console.log('Using JavaScript masonry fallback');
this.grid.classList.add('masonry-fallback');
this.calculateGridLayout();
}
}
/**
* Process all items in the grid
*/
processItems() {
const items = this.grid.querySelectorAll('.masonry-item');
items.forEach((item, index) => {
item.classList.add('loading');
const img = item.querySelector('img');
if (!img) {
item.classList.remove('loading');
this.setItemDimensions(item);
return;
}
// Wait for image to load
if (img.complete) {
this.onImageLoaded(img, item);
} else {
img.addEventListener('load', () => {
this.onImageLoaded(img, item);
});
img.addEventListener('error', () => {
this.onImageError(item);
});
}
});
}
/**
* Handle successful image load
*/
onImageLoaded(img, item) {
item.classList.remove('loading');
this.setItemDimensions(item, img);
if (!this.supportsNativeMasonry) {
this.recalculateLayout();
}
}
/**
* Handle image load error
*/
onImageError(item) {
item.classList.add('error');
item.classList.remove('loading');
console.warn('Failed to load image');
}
/**
* Calculate item dimensions based on image aspect ratio
*/
setItemDimensions(item, img = null) {
if (!img) return;
const naturalWidth = img.naturalWidth;
const naturalHeight = img.naturalHeight;
const aspectRatio = naturalHeight / naturalWidth || 1;
// Calculate rows based on aspect ratio
let rows = 1;
if (aspectRatio > 1.2) {
rows = 2;
}
if (aspectRatio > 1.8) {
rows = 3;
}
// Cap the maximum rows
rows = Math.min(rows, 3);
// Calculate columns
let cols = 1;
if (aspectRatio < 0.6) {
cols = 2;
}
// Store dimensions
item.dataset.rows = rows;
item.dataset.cols = cols;
item.dataset.aspectRatio = aspectRatio.toFixed(2);
// Update grid if not using native masonry
if (!this.supportsNativeMasonry) {
this.updateItemPosition(item);
}
}
/**
* Calculate grid layout for fallback
*/
calculateGridLayout() {
const width = this.grid.offsetWidth;
const columns = Math.floor((width + this.gap) / (this.columnWidth + this.gap));
const actualColumnWidth = (width - this.gap * (columns - 1)) / columns;
this.grid.style.display = 'grid';
this.grid.style.gridTemplateColumns = `repeat(${columns}, 1fr)`;
this.grid.style.gap = `${this.gap}px`;
this.grid.style.gridAutoRows = `${this.minRowHeight}px`;
this.grid.style.gridAutoFlow = 'dense';
this.currentColumns = columns;
this.currentColumnWidth = actualColumnWidth;
}
/**
* Update individual item position
*/
updateItemPosition(item) {
const rows = parseInt(item.dataset.rows) || 1;
const cols = parseInt(item.dataset.cols) || 1;
item.style.gridRowEnd = `span ${rows}`;
item.style.gridColumnEnd = `span ${cols}`;
}
/**
* Recalculate layout for all items
*/
recalculateLayout() {
this.calculateGridLayout();
const items = this.grid.querySelectorAll('.masonry-item');
items.forEach(item => this.updateItemPosition(item));
}
/**
* Setup ResizeObserver for responsive behavior
*/
setupObservers() {
// Resize observer
if ('ResizeObserver' in window) {
this.resizeObserver = new ResizeObserver(() => {
if (!this.supportsNativeMasonry) {
this.recalculateLayout();
}
});
this.resizeObserver.observe(this.grid);
}
// Mutation observer for dynamically added items
if ('MutationObserver' in window) {
this.mutationObserver = new MutationObserver(() => {
this.processItems();
this.recalculateLayout();
});
this.mutationObserver.observe(this.grid, {
childList: true,
subtree: false
});
}
}
/**
* Attach event listeners
*/
attachEventListeners() {
window.addEventListener('resize', () => {
if (!this.supportsNativeMasonry) {
this.recalculateLayout();
}
});
// Click handler for items
this.grid.addEventListener('click', (e) => {
const item = e.target.closest('.masonry-item');
if (item) {
this.handleItemClick(item);
}
});
}
/**
* Handle item click
*/
handleItemClick(item) {
const img = item.querySelector('img');
if (img) {
console.log('Clicked:', img.alt);
// Trigger lightbox or navigation
this.openLightbox(img);
}
}
/**
* Simple lightbox implementation
*/
openLightbox(img) {
const modal = document.createElement('div');
modal.className = 'lightbox';
modal.innerHTML = `
<div class="lightbox-content">
<button class="lightbox-close">×</button>
<img src="${img.src}" alt="${img.alt}">
</div>
`;
modal.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.9);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
`;
const content = modal.querySelector('.lightbox-content');
content.style.cssText = `
position: relative;
max-height: 90vh;
max-width: 90vw;
`;
const closeBtn = modal.querySelector('.lightbox-close');
closeBtn.style.cssText = `
position: absolute;
top: 20px;
right: 30px;
font-size: 40px;
color: white;
background: none;
border: none;
cursor: pointer;
z-index: 1001;
`;
const imgElement = modal.querySelector('img');
imgElement.style.cssText = `
max-height: 90vh;
max-width: 90vw;
object-fit: contain;
`;
modal.addEventListener('click', (e) => {
if (e.target === modal || e.target === closeBtn) {
document.body.removeChild(modal);
}
});
document.body.appendChild(modal);
}
/**
* Add new items to the grid
*/
addItems(items) {
items.forEach(itemHTML => {
const wrapper = document.createElement('div');
wrapper.innerHTML = itemHTML;
this.grid.appendChild(wrapper.firstChild);
});
this.processItems();
}
/**
* Remove item from grid
*/
removeItem(index) {
const items = this.grid.querySelectorAll('.masonry-item');
if (items[index]) {
items[index].remove();
this.recalculateLayout();
}
}
/**
* Clear all items
*/
clear() {
this.grid.innerHTML = '';
}
/**
* Get grid statistics
*/
getStats() {
const items = this.grid.querySelectorAll('.masonry-item');
return {
totalItems: items.length,
supportsNativeMasonry: this.supportsNativeMasonry,
columns: this.currentColumns,
gap: this.gap,
minRowHeight: this.minRowHeight
};
}
/**
* Destroy the masonry grid
*/
destroy() {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
}
if (this.mutationObserver) {
this.mutationObserver.disconnect();
}
}
}
// ===== Initialization =====
document.addEventListener('DOMContentLoaded', () => {
// Initialize with custom options
const masonry = new MasonryGrid({
gridId: 'masonryGrid',
minRowHeight: 200,
gap: 16,
columnWidth: 250,
maxRatio: 2
});
// Make it globally accessible for debugging
window.masonryGrid = masonry;
// Log stats
console.log('Masonry Grid initialized:', masonry.getStats());
// Example: Add new items dynamically
setTimeout(() => {
// Uncomment to test dynamic addition
// const newItems = Array(3).fill(`
// <figure class="masonry-item">
// <img src="https://picsum.photos/300/400?random=${Math.random()}" alt="New item">
// <figcaption>New Item</figcaption>
// </figure>
// `);
// masonry.addItems(newItems);
}, 2000);
});
/**
* Advanced Masonry Features
* - Infinity scroll
* - Lazy loading
* - Filter/Search
*/
class AdvancedMasonry extends MasonryGrid {
constructor(options = {}) {
super(options);
this.infiniteScroll = options.infiniteScroll !== false;
this.lazyLoad = options.lazyLoad !== false;
this.filterOptions = options.filterOptions || [];
this.currentPage = 1;
this.itemsPerPage = options.itemsPerPage || 12;
this.initAdvancedFeatures();
}
/**
* Initialize advanced features
*/
initAdvancedFeatures() {
if (this.infiniteScroll) {
this.setupInfiniteScroll();
}
if (this.lazyLoad) {
this.setupLazyLoading();
}
if (this.filterOptions.length > 0) {
this.setupFilters();
}
}
/**
* Setup infinite scroll
*/
setupInfiniteScroll() {
if (!('IntersectionObserver' in window)) return;
const sentinel = document.createElement('div');
sentinel.className = 'infinite-scroll-sentinel';
this.grid.appendChild(sentinel);
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) {
this.loadMoreItems();
}
},
{ threshold: 0.1 }
);
observer.observe(sentinel);
}
/**
* Setup lazy loading for images
*/
setupLazyLoading() {
if (!('IntersectionObserver' in window)) {
// Fallback for older browsers
this.lazyLoadFallback();
return;
}
const images = this.grid.querySelectorAll('img[data-src]');
const imageObserver = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.removeAttribute('data-src');
imageObserver.unobserve(img);
}
});
},
{ rootMargin: '50px' }
);
images.forEach(img => imageObserver.observe(img));
}
/**
* Fallback lazy loading for older browsers
*/
lazyLoadFallback() {
const images = this.grid.querySelectorAll('img[data-src]');
images.forEach(img => {
img.src = img.dataset.src;
img.removeAttribute('data-src');
});
}
/**
* Setup filtering system
*/
setupFilters() {
const filterContainer = document.createElement('div');
filterContainer.className = 'filter-controls';
filterContainer.style.cssText = `
display: flex;
gap: 0.5rem;
margin-bottom: 2rem;
flex-wrap: wrap;
`;
this.filterOptions.forEach(option => {
const btn = document.createElement('button');
btn.textContent = option;
btn.className = 'filter-btn';
btn.style.cssText = `
padding: 0.5rem 1rem;
border: 2px solid #3498db;
background: white;
color: #3498db;
border-radius: 20px;
cursor: pointer;
transition: all 0.3s;
font-weight: 500;
`;
btn.addEventListener('click', () => {
this.filterItems(option);
document.querySelectorAll('.filter-btn').forEach(b => {
b.style.background = 'white';
b.style.color = '#3498db';
});
btn.style.background = '#3498db';
btn.style.color = 'white';
});
filterContainer.appendChild(btn);
});
this.grid.parentElement.insertBefore(filterContainer, this.grid);
}
/**
* Filter items by category
*/
filterItems(category) {
const items = this.grid.querySelectorAll('.masonry-item');
items.forEach(item => {
if (category === 'All' || item.dataset.category === category) {
item.style.display = '';
item.style.animation = 'fadeIn 0.3s';
} else {
item.style.display = 'none';
}
});
if (!this.supportsNativeMasonry) {
this.recalculateLayout();
}
}
/**
* Load more items dynamically
*/
loadMoreItems() {
console.log(`Loading more items (page ${this.currentPage})`);
const newItems = this.generateMockItems(this.itemsPerPage);
this.addItems(newItems);
this.currentPage++;
}
/**
* Generate mock items for demo
*/
generateMockItems(count) {
const items = [];
for (let i = 0; i < count; i++) {
items.push(`
<figure class="masonry-item">
<img src="https://picsum.photos/300/${300 + Math.random() * 200}?random=${Math.random()}"
alt="Gallery item">
<figcaption>Item ${i + 1}</figcaption>
</figure>
`);
}
return items;
}
}
// ===== Initialization with Advanced Features =====
document.addEventListener('DOMContentLoaded', () => {
const masonry = new AdvancedMasonry({
gridId: 'masonryGrid',
infiniteScroll: true,
lazyLoad: true,
filterOptions: ['All', 'Nature', 'Architecture', 'Portrait'],
itemsPerPage: 8,
minRowHeight: 200,
gap: 16
});
window.advancedMasonry = masonry;
});
// Fade in animation
const style = document.createElement('style');
style.textContent = `
@keyframes fadeIn {
from {
opacity: 0;
transform: scale(0.9);
}
to {
opacity: 1;
transform: scale(1);
}
}
`;
document.head.appendChild(style);