Render Charts 100% Width In Boostrap Tabs

The problem 

You would like to render charts at 100% width (Google Charts, Highcharts, CanvaJS, or other favorite charts) when the user clicks on a tab in Boostrap.

Even though your CSS or inline style set to width: 100%, the chart is rendered wider or smaller than the width of the tab.

Why is this happening?

Bootstrap tabs use the display property to toggle the tab visibility.

.tab-content > .tab-pane {
  display: none;
}

When the display property is set to none, it is not possible to determine the width of the tab. Instead, the chart is then rendered at a default width, which varies depending on the chart library you are using.

The Solution

There are a number of solutions that I have explored, including a number of Javascript hacks like re-rendering the chart when clicking the tab or rendering the chart again when the user scales the browser window.

Then I came across a pure CSS solution. Big thanks to ryenus over on Stack Overflow!

.tab-content > .tab-pane,
.pill-content > .pill-pane {
    display: block;     
    height: 0;          
    overflow-y: hidden; 
}

.tab-content > .active,
.pill-content > .active {
    height: auto;       
} 

This simple solution overrides the hidden display property, sets the height to zero pixels, and hides scrollbars. This is effectively makes the tab invisible to the user.

The chart is able to render correctly to the width of the tab. We then need to change the height of the chart when the tab is active, which is done by setting the height property.

Thanks again to ryenus for this brilliant solution.

7 Comments on “Render Charts 100% Width In Boostrap Tabs”

Leave a Reply