Why are Bootstrap tabs displaying tab-pane divs with incorrect widths when using highcharts?

前端 未结 6 1251
长发绾君心
长发绾君心 2020-11-22 14:30

So I\'m creating a page with tabbed content using Twitter\'s Bootstrap, yet the content of my starting active div is always different than that of my other tabs. For example

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 14:39

    The Cause

    This is not a Highcharts issue, at least not by itself, the problem is caused by the fact that Bootstrap uses display: none to hide inactive tabs:

    .tab-content > .tab-pane, .pill-content > .pill-pane {
        display: none;      /* this is the problem */
    }
    

    This causes Highcharts not able to get the expected width to initialize the chart, thus defaults to 600px. This would happen to other tools using the same approach to hide content.

    A Pure CSS Solution

    Instead of working around the issue with an extra redraw or delayed initialization, we can achieve the hidden effect using height: 0; overflow-y: hidden, this way the hidden tab panes are still in place and having valid width:

    /* bootstrap hack: fix content width inside hidden tabs */
    .tab-content > .tab-pane:not(.active),
    .pill-content > .pill-pane:not(.active) {
        display: block;
        height: 0;
        overflow-y: hidden;
    } 
    /* bootstrap hack end */
    

    Update: We now target inactive tabs directly, via :not(.active), to avoid possible side effect if any.

    This solution is seamless, so you no longer have to worry whether the chart is inside a tab-pane or not. And it's efficient as it fixes the width issue in the first place, thus there's no need to workaround the width issue afterward via resize/redraw/reflow using javascript.

    Note about cascading order

    This patch needs to be loaded after bootstrap css, because of CSS cascading order rules, in short, the latter rule wins.

    Demo

    Before vs After

    Tip: switch to the Profile tab to see the difference.

提交回复
热议问题