Bootstrap - Masonry Demo

Introduction to Bootstrap Masonry

Hello, aspiring web developers! Today, we're going to dive into the exciting world of Bootstrap Masonry. As your friendly neighborhood computer teacher, I'm thrilled to guide you through this journey. Even if you've never written a line of code before, don't worry – we'll take it step by step, and soon you'll be creating beautiful, dynamic layouts like a pro!

Bootstrap-Masonry Demo

What is Bootstrap Masonry?

Bootstrap Masonry is a powerful layout technique that allows you to create a grid of elements with varying heights. Imagine a wall of differently sized bricks fitting together perfectly – that's the essence of Masonry! It's particularly useful for creating image galleries, portfolios, or any content where you want a neat, organized look without wasting space.

Getting Started with Bootstrap Masonry

Setting Up Your Project

Before we dive into the code, let's set up our project. We'll need to include Bootstrap and the Masonry library in our HTML file. Don't worry if this seems confusing at first – I'll explain each part as we go along.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bootstrap Masonry Demo</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <!-- Our content will go here -->

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/masonry.pkgd.min.js"></script>
</body>
</html>

Let's break this down:

  1. We start with the basic HTML structure.
  2. In the <head>, we link to the Bootstrap CSS file.
  3. At the bottom of the <body>, we include the Bootstrap and Masonry JavaScript files.

These files give us the tools we need to create our Masonry layout.

Creating Your First Masonry Layout

Now, let's create a simple Masonry layout with some colorful boxes. We'll add this code inside the <body> tag:

<div class="container my-5">
    <div class="row" data-masonry='{"percentPosition": true }'>
        <div class="col-sm-6 col-lg-4 mb-4">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <h5 class="card-title">Box 1</h5>
                    <p class="card-text">This is a short box.</p>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-lg-4 mb-4">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <h5 class="card-title">Box 2</h5>
                    <p class="card-text">This box is a bit taller. Masonry will adjust!</p>
                    <p class="card-text">Look how nicely it fits.</p>
                </div>
            </div>
        </div>
        <!-- Add more boxes here -->
    </div>
</div>

Let's break this down:

  1. We create a container with a row inside.
  2. The data-masonry='{"percentPosition": true }' attribute tells Bootstrap to use Masonry layout for this row.
  3. Each box is a column (col-sm-6 col-lg-4) with a card inside.
  4. We use different background colors (bg-primary, bg-success) to make our boxes visually distinct.

Customizing Your Masonry Layout

Now that we have our basic layout, let's explore some ways to customize it.

Adding Different Sized Elements

One of the beauties of Masonry is how it handles elements of different sizes. Let's add a few more boxes with varying content:

<div class="col-sm-6 col-lg-4 mb-4">
    <div class="card bg-warning">
        <div class="card-body">
            <h5 class="card-title">Box 3</h5>
            <p class="card-text">This is a really tall box!</p>
            <p class="card-text">It has lots of content.</p>
            <p class="card-text">Masonry will make sure it fits perfectly.</p>
            <p class="card-text">No matter how tall it gets.</p>
        </div>
    </div>
</div>
<div class="col-sm-6 col-lg-4 mb-4">
    <div class="card bg-info">
        <div class="card-body">
            <h5 class="card-title">Box 4</h5>
            <p class="card-text">Back to a short box.</p>
        </div>
    </div>
</div>

Adding Images to Your Masonry Layout

Masonry is great for image galleries. Let's add some images to our layout:

<div class="col-sm-6 col-lg-4 mb-4">
    <div class="card">
        <img src="https://picsum.photos/300/200" class="card-img-top" alt="Random image">
        <div class="card-body">
            <h5 class="card-title">Image Card</h5>
            <p class="card-text">This card has an image.</p>
        </div>
    </div>
</div>

This code adds a card with a random image from Lorem Picsum. The image will load at 300x200 pixels, but you can adjust these numbers to get different sized images.

Advanced Techniques

Filtering Masonry Items

One cool feature we can add is the ability to filter our Masonry items. Let's add some category buttons and give our items categories:

<div class="container my-5">
    <div class="mb-3">
        <button class="btn btn-primary filter-btn" data-filter="all">All</button>
        <button class="btn btn-secondary filter-btn" data-filter="category1">Category 1</button>
        <button class="btn btn-secondary filter-btn" data-filter="category2">Category 2</button>
    </div>
    <div class="row" id="masonry-grid" data-masonry='{"percentPosition": true }'>
        <div class="col-sm-6 col-lg-4 mb-4 masonry-item" data-category="category1">
            <!-- Item content -->
        </div>
        <div class="col-sm-6 col-lg-4 mb-4 masonry-item" data-category="category2">
            <!-- Item content -->
        </div>
        <!-- More items... -->
    </div>
</div>

To make this work, we need to add some JavaScript:

<script>
document.addEventListener('DOMContentLoaded', function() {
    var grid = document.querySelector('#masonry-grid');
    var msnry = new Masonry(grid, {
        percentPosition: true
    });

    var filterButtons = document.querySelectorAll('.filter-btn');
    filterButtons.forEach(function(button) {
        button.addEventListener('click', function() {
            var filterValue = this.getAttribute('data-filter');
            var items = grid.querySelectorAll('.masonry-item');

            items.forEach(function(item) {
                if (filterValue === 'all' || item.getAttribute('data-category') === filterValue) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });

            msnry.layout();
        });
    });
});
</script>

This script does the following:

  1. Initializes Masonry on our grid.
  2. Adds click event listeners to our filter buttons.
  3. When a button is clicked, it shows/hides items based on their category.
  4. After filtering, it calls msnry.layout() to rearrange the visible items.

Conclusion

Congratulations! You've just created your first Bootstrap Masonry layout. From basic grids to advanced filtering, you now have the tools to create dynamic, responsive layouts that will make your web pages stand out.

Remember, the key to mastering web development is practice. Try experimenting with different content, layouts, and features. Don't be afraid to break things – that's often how we learn the most valuable lessons in coding.

Keep building, keep learning, and most importantly, have fun with it! Before you know it, you'll be creating web layouts that would make even the most skilled masons jealous. Happy coding!

Method Description
Masonry(element[, options]) Initialize Masonry on an element
msnry.layout() Trigger layout after making changes
msnry.appended(elements) Add and lay out newly appended item elements
msnry.prepended(elements) Add and lay out newly prepended item elements
msnry.destroy() Remove Masonry functionality completely

Credits: Image by storyset