Home >Web Front-end >CSS Tutorial >Getting Bootstrap Tabs to Play Nice with Masonry

Getting Bootstrap Tabs to Play Nice with Masonry

Lisa Kudrow
Lisa KudrowOriginal
2025-02-15 08:31:11765browse

Getting Bootstrap Tabs to Play Nice with Masonry

Key Points

  • Bootstrap and Masonry are both powerful web development tools, but using them at the same time can cause layout errors, especially if you hide tabs.
  • Masonry, a JavaScript grid layout library, is a viable solution for creating a card grid with inequality even if there are certain browser compatibility issues.
  • Integrating the Bootstrap tab with Masonry is not easy. The grid inside the default active tab panel may appear correctly, but clicking the tab navigation link to show the contents of the hidden panel may cause the grid items to be stacked incorrectly.
  • The solution to the layout error is to reinitialize the Masonry library after each panel is visible. This can be achieved by using the "shown.bs.tab" event. With this solution, it's easier to create a great tile layout.

Bootstrap is one of the most widely adopted open source front-end frameworks. Include Bootstrap in your project and you will be able to create responsive web pages immediately. If you try to use Masonry with the Bootstrap tab widget (one of the many JavaScript components that Bootstrap provides), you will most likely encounter some kind of annoying behavior.

On the Masonry website, we read that Masonry is…

A JavaScript grid layout library. It works by placing elements in the optimal position based on the available vertical space, a bit like a mason building a stone on a wall.

I did run into this problem and this article focuses on where the problem lies and what solutions you can take.

Detailed explanation of Bootstrap tab

The Bootstrap tab component contains two key related parts: the tab navigation element and multiple content panels. When the page loads, the first panel applies the .active class. This makes the panel visible by default. This class is used through JavaScript to toggle the visibility of the panel through the tab navigation link contact event: if .active exists, the panel is visible, otherwise the panel is hidden.

If you have some web content that is best rendered in separate blocks rather than all squeezed in one place, the Bootstrap tab component may come in handy.

Why choose Masonry?

In some cases, the content within each panel is suitable for display in a responsive grid layout. For example, a range of product, service, and portfolio projects are content types that can be displayed in a grid format.

However, if the heights of the grid cells are not equal, the following may occur.

Getting Bootstrap Tabs to Play Nice with Masonry

There is a large gap between the two content lines and the layout looks damaged.

Bootstrap solves the monospace problem with the new card component based on Flexbox. Just adding the card-deck class to a set of card components is enough to implement monospace columns.

If you want the card length to be inconsistent, you can use CSS3 multi-column layout. (After all, it's pretty good overall, even with some browser compatibility issues.) This is the basis for the new card column options available with the card components. However, if you still like the beautiful animations out of the box of the Masonry JavaScript library and its extensive browser compatibility, JavaScript is still a viable option in this case.

Set the demo page

Starting a demo page helps to illustrate that integrating the Bootstrap tab with Masonry is not as simple as expected.

The demo page of this article is based on the starter templates provided on the Bootstrap website.

The following is the framework marked by the Bootstrap tab component:

<code class="language-html"><ul class="nav nav-tabs" id="myTab" role="tablist">
  <li class="nav-item">
    <a class="nav-link active" id="home-tab" data-toggle="tab" href="https://www.php.cn/link/6fbb2c2ee065c77a193d0057aab8fa11" role="tab" aria-controls="home" aria-selected="true">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="profile-tab" data-toggle="tab" href="https://www.php.cn/link/0bd97cb91b8d57dad18542081fb8f2b1" role="tab" aria-controls="profile" aria-selected="false">Profile</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="contact-tab" data-toggle="tab" href="https://www.php.cn/link/18fb150bb65a5825c83969a59f3febc1" role="tab" aria-controls="contact" aria-selected="false">Contact</a>
  </li>
</ul></code>

nav The nav-tabs class is responsible for giving the khaki a unique appearance. The value of the href attribute forms the relationship between a single tab and its corresponding tab content. For example, a href value of https://www.php.cn/link/6fbb2c2ee065c77a193d0057aab8fa11 will establish a relationship with the content of the tab in the div with id value of home: Clicking the specific tab will display the content in the div.

In addition, please note how Bootstrap focuses on accessibility properties such as role, aria-controls, etc.

The following code snippet illustrates the structure of the tab content:

<code class="language-html"><div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
  <h3>Tab 1 Content</h3>
  <div class="card-group">
    <div class="card">
      <img src="https://img.php.cn/" alt="Getting Bootstrap Tabs to Play Nice with Masonry ">
      <div class="card-body">
        <h5 class="card-title">Card title</h5>
        <p class="card-text">Card text here.</p>
        <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
      </div>
    </div>
    <div class="card">
      </div>
    <div class="card">
      </div>
  </div>
</div></code>

Simply add a similar structure to each tab content part corresponding to the tab element written above.

For the full code, check out the CodePen demo.

Add Masonry library

You can download Masonry from the official website by clicking the "Download masonry.pkgd.min.js" button.

To avoid layout issues, the library's author recommends using Masonry with the imagesLoaded plugin.

Masonry does not require a jQuery library to work. However, since the Bootstrap JavaScript component already uses jQuery, I will make life easier and initialize Masonry in jQuery way.

The following is a snippet of initializing Masonry using jQuery and imagesLoaded:

<code class="language-javascript">var $container = $('.masonry-container');
$container.imagesLoaded( function () {
  $container.masonry({
    columnWidth: '.card',
    itemSelector: '.card'
  });   
});  </code>

The above code caches the div that wraps all card elements in a variable named $container.

Next, use a few recommended options to initialize Masonry on $container. The columnWidth option indicates the width of the horizontal grid column. Here it is set to the width of a single card item by using its class name. The itemSelector option indicates which child elements to be used as project elements. Here, it is also set as a single card item.

It's time to test the code.

Oh! What's wrong with hiding the panel?

The above code works fine on web pages that do not use the Bootstrap tab. However, in this case, you will soon realize that something strange is going to happen.

First of all, it looks pretty good because the grid inside the default active tab panel is displayed correctly:

Getting Bootstrap Tabs to Play Nice with Masonry

However, if you click the tab navigation link to show the content of the hidden panel, the following happens:

Getting Bootstrap Tabs to Play Nice with Masonry

Viewing the source code will reveal that Masonry has been fired as expected, but the position of each item is calculated incorrectly: the grid items are all stacked together like a stack of cards.

And more than that. Resizing the browser window will cause the grid items to correctly position themselves.

Let's fix layout error

Since unexpected layout errors become apparent after clicking the tab navigation link, let's take a closer look at the events triggered by the Bootstrap tab.

The event list is very short. This is it.

  • show.bs.tab fires when the tab is displayed, but before the new tab is displayed
  • shown.bs.tab triggers
  • after the tab is displayed.
  • hide.bs.tab is fired when you want to display a new tab (so the previous active tab will be hidden)
  • hidden.bs.tab is fired after the new tab is displayed (so the previous active tab is hidden).

Because the Masonry layout becomes messy after the tab is displayed, select the show.bs.tab event. Here is the code you can put it directly below the previous code snippet:

<code class="language-html"><ul class="nav nav-tabs" id="myTab" role="tablist">
  <li class="nav-item">
    <a class="nav-link active" id="home-tab" data-toggle="tab" href="https://www.php.cn/link/6fbb2c2ee065c77a193d0057aab8fa11" role="tab" aria-controls="home" aria-selected="true">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="profile-tab" data-toggle="tab" href="https://www.php.cn/link/0bd97cb91b8d57dad18542081fb8f2b1" role="tab" aria-controls="profile" aria-selected="false">Profile</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="contact-tab" data-toggle="tab" href="https://www.php.cn/link/18fb150bb65a5825c83969a59f3febc1" role="tab" aria-controls="contact" aria-selected="false">Contact</a>
  </li>
</ul></code>

The following is what happens in the above code:

The

jQuery .each() function loops through each tab navigation link and listens for the shown.bs.tab event. When the event fires, the panel becomes visible and Masonry is reinitialized after all images are loaded.

Test code

If you've been following, start your demo in your browser, or try the CodePen demo below to see the results:

CodePen demo link

Click the tab navigation link and note how the grid project evenly fits each content panel this time. Resizing the browser will cause the project to correctly reposition itself with beautiful animation effects.

That's it, the work is done!

Conclusion

In this article, I demonstrated how to integrate the Bootstrap tab component with the Masonry JavaScript library.

Both scripts are easy to use and powerful. However, put them together and you will face some annoying layout errors that affect hidden tabs. As shown above, the trick is to re-initialize the Masonry library after each panel is visible.

With this solution, creating a great tile layout will be a breeze.

I wish you a happy use of Bootstrap!

Bootstrap tab and Masonry's FAQ (FAQ)

(The FAQ part should be inserted here, the content is consistent with the original FAQ part, and it will be slightly rewritten as needed to keep the semantic unchanged)

The above is the detailed content of Getting Bootstrap Tabs to Play Nice with Masonry. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn