Bootstrap - Masonry Demo

-

Masonry Layout

Basic Masonry Grid

To create a basic Masonry grid using Bootstrap, start by defining a container element that will hold the grid items. This container should have a class of container or container-fluid for proper sizing and alignment. Inside the container, create individual grid items using div elements. Each grid item can have varying heights and will be positioned automatically by the Masonry layout.

Apply the Masonry JavaScript to the container element. You can do this by including the Masonry library in your project and initializing it on the container using JavaScript code.

Example: HTML

<div class="container" id="masonry-grid">
  <div class="grid-item">...</div>
  <div class="grid-item">...</div>
  <div class="grid-item">...</div>
  ...
</div>
var masonryGrid = document.getElementById('masonry-grid');
var masonry = new Masonry(masonryGrid, {
  // options
  itemSelector: '.grid-item',
  columnWidth: '.grid-sizer',
  percentPosition: true
});

In the JavaScript code, we select the container element using its ID and create a new Masonry instance, specifying the item selector and other options as needed.

Customizing Masonry Options

Masonry provides several options to customize the layout and behavior of the grid. Here are a few commonly used options:

  1. Column Width and Gutter Size: You can adjust the width of the columns and the size of the gutters between grid items using the columnWidth and gutter options.

Example: JavaScript

var masonry = new Masonry(masonryGrid, {
  columnWidth: '.grid-sizer',
  gutter: 20
});

This sets the column width to match the width of an element with the class grid-sizer and sets the gutter size to 20 pixels.

  1. Layout Mode: Masonry supports two layout modes: fitWidth and masonry. The fitWidth mode resizes the container to fit the available width, while the masonry mode maintains the original container size. You can set the layout mode using the layoutMode option:

Example: JavaScript

var masonry = new Masonry(masonryGrid, {
  layoutMode: 'fitWidth'
});
  1. Resize Handling: By default, Masonry automatically updates the layout when the window is resized. However, you can enable or disable this behavior using the resizeable option:

Example: JavaScript

var masonry = new Masonry(masonryGrid, {
  resizeable: false
});

Setting resizeable to false disables the automatic layout update on window resize.

These are just a few examples of the options you can customize in Masonry. Refer to the Masonry documentation for a complete list of available options and their usage.

Responsive Masonry Grid

To make your Masonry grid responsive and adapt to different screen sizes, you can use Bootstrap's responsive classes with Masonry's layout options.

Apply Bootstrap's responsive classes to the grid items.

Example

<div class="container" id="masonry-grid">
  <div class="grid-item col-sm-6 col-md-4">...</div>
  <div class="grid-item col-sm-6 col-md-4">...</div>
  <div class="grid-item col-sm-6 col-md-4">...</div>
  ...
</div>

Next, update the Masonry layout when the window is resized. By default, Masonry handles window resizing, but you can trigger the layout update using the layout() method.

Example

var masonryGrid = document.getElementById('masonry-grid');
var masonry = new Masonry(masonryGrid, {
  itemSelector: '.grid-item',
  columnWidth: '.grid-sizer',
  percentPosition: true
});

window.addEventListener('resize', function() {
  masonry.layout();
});

By combining Bootstrap's responsive classes and Masonry's layout options, you can create a responsive Masonry grid that adapts to different screen widths. The grid items will reposition and adjust their sizes, providing an optimal viewing experience across devices.

Loading Content Dynamically

In many scenarios, you may need to load content dynamically into your Masonry grid, such as fetching data from an API or getting it from a database. Masonry provides methods to append new items to the grid and update the layout accordingly.

To fetch data from an API or database, you can use JavaScript's built-in fetch() function or libraries like jQuery's $.ajax(). Once you have the data, you can create new grid items and append them to the Masonry container.

Example: Fetching data from an API and appending new items to the Masonry grid

var masonryGrid = document.getElementById('masonry-grid');
var masonry = new Masonry(masonryGrid, {
  itemSelector: '.grid-item',
  columnWidth: '.grid-sizer',
  percentPosition: true
});

// Fetch data from an API
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // Create new grid items
    var newItems = data.map(item => {
      var itemElement = document.createElement('div');
      itemElement.className = 'grid-item';
      itemElement.innerHTML = `<h3>${item.title}</h3><p>${item.description}</p>`;
      return itemElement;
    });

    // Append new items to the Masonry grid
    masonryGrid.append(...newItems);

    // Trigger Masonry layout update
    masonry.appended(newItems);
    masonry.layout();
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

We fetch data from an API using the fetch() function. Once the data is retrieved, we create new grid items by mapping over the data and creating div elements with the necessary class and content.

We then use Masonry's append() method to add the new items to the Masonry container. After appending the items, we need to trigger the Masonry layout update to properly position the new items. We use the appended() method to inform Masonry about the newly added items, and then call the layout() method to update the layout.

Tip: Performance consideration

When loading content dynamically, you should consider the performance impact of fetching and rendering large amounts of data. You can implement techniques like lazy loading or infinite scrolling to load content gradually as the user scrolls down the page.

Filtering and Sorting

Masonry lets you add filtering and sorting to improve the user experience and help users find items in the grid.

To filter, create filter buttons or a dropdown menu for users to select a category or criteria. When a filter is selected, show or hide the matching grid items based on their attributes.

Example: Filtering in a Masonry grid

<div class="filters">
  <button class="filter-button" data-filter="all">All</button>
  <button class="filter-button" data-filter=".category-1">Category 1</button>
  <button class="filter-button" data-filter=".category-2">Category 2</button>
  <button class="filter-button" data-filter=".category-3">Category 3</button>
</div>

<div class="container" id="masonry-grid">
  <div class="grid-item category-1">...</div>
  <div class="grid-item category-2">...</div>
  <div class="grid-item category-1">...</div>
  <div class="grid-item category-3">...</div>
  ...
</div>
var masonryGrid = document.getElementById('masonry-grid');
var masonry = new Masonry(masonryGrid, {
  itemSelector: '.grid-item',
  columnWidth: '.grid-sizer',
  percentPosition: true
});

var filterButtons = document.querySelectorAll('.filter-button');
filterButtons.forEach(button => {
  button.addEventListener('click', function() {
    var filterValue = this.getAttribute('data-filter');

    if (filterValue === 'all') {
      masonry.items.forEach(item => item.element.style.display = 'block');
    } else {
      masonry.items.forEach(item => {
        if (item.element.classList.contains(filterValue.slice(1))) {
          item.element.style.display = 'block';
        } else {
          item.element.style.display = 'none';
        }
      });
    }

    masonry.layout();
  });
});

The example has filter buttons with data-filter attributes for the category to filter. When a filter button is clicked, its data-filter value is used to show or hide the Masonry items based on their category class.

After updating the grid items' visibility, call layout() to update the Masonry layout based on the filtered items.

To sort, provide options for users to sort the grid items based on criteria like alphabetical order, date, or other attributes. When a sorting option is selected, rearrange the order of the grid items in the Masonry container.

Example: Sorting in a Masonry grid

var sortButtons = document.querySelectorAll('.sort-button');
sortButtons.forEach(button => {
  button.addEventListener('click', function() {
    var sortValue = this.getAttribute('data-sort');

    var sortedItems = Array.from(masonry.items).sort((a, b) => {
      var aValue = a.element.getAttribute('data-' + sortValue);
      var bValue = b.element.getAttribute('data-' + sortValue);
      return aValue.localeCompare(bValue);
    });

    sortedItems.forEach(item => masonryGrid.appendChild(item.element));

    masonry.reloadItems();
    masonry.layout();
  });
});

The example has sort buttons with data-sort attributes for the sorting criteria. When a sort button is clicked, its data-sort value is used to sort the Masonry items based on their data-* attributes.

Convert the Masonry items to an array, sort them using sort() and a comparison function, then append the sorted items back to the Masonry container in the new order.

Call reloadItems() to reload the Masonry items and layout() to update the layout based on the new order.

By adding filtering and sorting to your Masonry grid, you give users tools to find the content they want, improving the user experience of your website or application.

Animations and Transitions

You can add animations and transitions to your Masonry grid to make it more visually appealing and engaging. Animations can be applied to grid items, while transitions can be used for smooth layout changes when items are added, removed, or resized.

Adding Animations to Grid Items

You can use CSS animations to animate your grid items. CSS has animation properties that let you set the animation's duration, timing function, and keyframes.

Example: Adding a fade-in animation to grid items

.grid-item {
  opacity: 0;
  animation: fadeIn 0.5s ease-in-out forwards;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

The grid items start with an opacity of 0 and are moved 20 pixels down. The fadeIn animation is applied to the items, which increases the opacity to 1 and moves the items back to their original position over 0.5 seconds.

Using CSS Transitions for Smooth Layout Changes

When the Masonry layout changes, such as when items are added, removed, or resized, you can use CSS transitions to create smooth transitions between the old and new layouts.

Example: Applying a transition to the transform property of grid items

.grid-item {
  transition: transform 0.3s ease-in-out;
}

By applying a transition to the transform property of the grid items, the items will smoothly move to their new positions when the layout changes. You can change the duration and timing function of the transition to get the effect you want.

Integrating with Third-Party Animation Libraries

For more complex animations, you can integrate Masonry with animation libraries like Animate.css or GreenSock (GSAP). These libraries have many pre-built animations and tools for making custom animations.

Example: Using Animate.css with Masonry

<div class="grid-item wow fadeInUp">...</div>
var masonry = new Masonry(masonryGrid, {
  // Masonry options
});

new WOW().init();

The wow class is added to the grid items, and the fadeInUp animation class from Animate.css is applied. The WOW library is then initialized to start the animations when the items are in the viewport.

You can also use GreenSock to create complex animations and control them with JavaScript. GreenSock has many animation methods and properties that you can use to animate grid items, create staggered animations, and more.

By adding animations and transitions to Masonry, you can create dynamic and visually appealing grids that grab users' attention and improve their experience on your website or application.