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.
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:
<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="http://ipnx.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="http://ipnx.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="http://ipnx.cn/link/18fb150bb65a5825c83969a59f3febc1" role="tab" aria-controls="contact" aria-selected="false">Contact</a> </li> </ul>
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 http://ipnx.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:
<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="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" 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>
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:
var $container = $('.masonry-container'); $container.imagesLoaded( function () { $container.masonry({ columnWidth: '.card', itemSelector: '.card' }); });
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:
However, if you click the tab navigation link to show the content of the hidden panel, the following happens:
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:
<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="http://ipnx.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="http://ipnx.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="http://ipnx.cn/link/18fb150bb65a5825c83969a59f3febc1" role="tab" aria-controls="contact" aria-selected="false">Contact</a> </li> </ul>
The following is what happens in the above code:
ThejQuery .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:
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.
