Highcharts width exceeds container div on first load
Asked Answered
O

22

38

I'm using Highcharts with jQuery Mobile.

I have an area graph being drawn within a jQM data-role="content" container and within that container I have the following divs:

<div style="padding-top: 5px; padding-bottom: 10px; position: relative; width: 100%;">
    <div id="hg_graph" style="width: 100%"></div>
</div>

My highcharts graph is a basic graph taken from one of their examples where I have not set the chart width property.

On the first load the graph exceeds the width of the containing divs, but when I resize the browser it snaps to the appropriate width.

How can I make it so that the width of it is right on first page load and not just on resize?

I've reviewed similar posts on stack overflow and none of the solutions seem to work.

UPDATES

  1. I've identified the problem is that the dynamically generated <rect> tag by Highcharts is taking the full width of the browser window on page load and not taking it from the containiner div width at all. Here's the html generated when I inspect:

    <rect rx="5" ry="5" fill="#FFFFFF" x="0" y="0" **width="1920"** height="200"></rect>

  2. I tried to reproduce in JSFiddle, but it seems to work fine there, which really has me stumped. Here's my JSFiddle code: http://jsfiddle.net/meandnotyou/rMXnY

Odeen answered 14/8, 2013 at 19:10 Comment(4)
So prolebm is resolved, am I right ?Gravitation
@SebastianBochan No. It's not resolved. The most upvoted answer just cuts off the graph!Jaclynjaco
Still not yet resolved. Is this problem already post as issue in its GitHub Repository?Aeriell
I'm stuck with this sh** too ! :(Snaffle
M
45

To call chart.reflow() helped me. Docs: http://api.highcharts.com/highcharts#Chart.reflow

Masakomasan answered 4/11, 2015 at 15:44 Comment(6)
This is the best answer. This is the correct way. This is the only thing that worked for me. Thannnnnks!!!!! Solved hours of frustrationJeu
I feel sorry for people who don't see this answer. UPVOTE THIS ANSWER!Stirk
How do you call chart.reflow()? I can't seem to find it in the documentation. I see the chart property but cannot find a method to call.Castigate
Here is the example: jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/… this.chart = new Highcharts.Chart(this.opts); this.chart.reflow();Masakomasan
Sorry but this doesn't work atleast in my case where 3 charts are placed side by side, however, the solution above works where width and height are set to 100%Acrobatic
For a CSS only workaround that might help see my solution https://mcmap.net/q/403796/-highcharts-width-exceeds-container-div-on-first-loadTowards
A
34

this works like magic

put in your css file following

.highcharts-container {
    width:100% !important;
    height:100% !important;
}
Acrobatic answered 23/7, 2014 at 22:7 Comment(9)
This hides part of the graphPeraea
Do you have any idea how long I spent on trying to get this to work for me. And it's as simple as this. Thank you so much!Durwood
Do you know why this works though? And why isn't it fixed in Highcharts?Billionaire
For me it worked using adding to highcharts-container position: absolute and the parent container position: relative together with this response.Picrotoxin
This doesn't make the chart fit, it simply forces it's container to not break out of it's parent container. This makes the chart extend past highcharts-container, which no longer shows a scrollbar. This is by no means a solution to the root problem.Qualmish
Its working width but data is not showing if i moved window screen data is coming first time data is now visableCurry
@ZaLiTHkA this doesn't make chart extend past container, infact chart fits inside container as the width and height of class "highcharts-container" are adjusted to parent by the codeAcrobatic
@comeOnGetIt I posted that comment after I tried your proposed solution, but I couldn't get it to work... it was a while back and I don't remember exact details, but looking back now, I suspect I may have had some other CSS rules affecting my test page.. just tried to remove my down-vote, but I can't unless the answer is edited, so if you do that please let me know.Qualmish
In vue: <highcharts :options="chartOptions" class="highchart-container"></highcharts> <style scoped>.highchart-container { width: 100% important; height: 100% !important;} </style>Natasha
A
13

I have the same problem, in my case had a graph of highchart that it is shown after click a button. I put $(window).resize(); after show event and it solved the problem correctly. I hope you serve.

Alderman answered 17/2, 2015 at 17:9 Comment(3)
I used the same, seems the most elegant solution on this page.Sculptress
For anyone having sizing issued because their Highchart starts out in a container that isn't displayed when the page loads, this approach will give you the most consistent results.Karlis
This is what I was doing, worked great until upgrading to version 6 :(Vilmavim
P
6

Set width of the chart. That's the only option that worked for me.

chart: {
            type: 'line',
            width: 835
        },
Plasticine answered 23/4, 2014 at 9:8 Comment(1)
Its worked only dynamically in large screens if we use responsive .?Curry
E
4

Define the highcharts inside the document ready:

<div style="width:50%" id="charts">

and the script:

$(document).ready(function(){
    $(#chart).highcharts(){
    ...
    });
)};

Hope it works ;)

Erastus answered 10/10, 2016 at 19:40 Comment(0)
P
3

I had a similar issue with centering the highcharts graph it gave. It would center and size correctly for some resolutions but not all. When it didn't, I had the exact same symptoms you're describing here.

I fixed it by attaching/overriding additional css to the highcharts default.

so in a custom css file, adding

.highcharts-container{
/** Rules it should follow **/
}

should fix your issue. Assuming that your div "hg=graph" has nothing but highcharts.

Pithos answered 14/8, 2013 at 19:18 Comment(5)
I've tried overriding the div that's holding the highchart graph with various properties, but can't seem to get it right. Can you post an example of the CSS rules you used? Also, I've updated my post with more info.Odeen
The one I used was {margin: 0 auto;} Since I wanted to center mine. There is a chance that the class you need to override isn't the one I mentioned. If you view source on your page, inspect your hg_graph div and find the underlying container that highcharts use.Pithos
Hi Tim.. I found the class and it is .highcharts-container. I've tried specifying width: 100% !important or editing inline in Chrome's DevTools, which does successfully restricts the container to the proper width now, but the graph is still 1920px wide and overflows, but hidden beyond the container. The problem seems to be that on first load the <SVG> element generated by Highcarts has a defined width in pixels, so changing the container doesn't really do anything as the graph will just overflow.Odeen
I'm sorry that I can't help you more, as I was simply building it for PC and not mobile. The other thing is that I'm not sure what you're trying to accomplish overall. Are you trying to limit the size of the graph by scale? Because 100% of a screen will be the entire screen, and 100% of that 100% is still that entire screen... So that might be your overflow?Pithos
Thanks for trying. I'm testing on Chrome on my PC right now, so it has nothing to do with mobile or not. Basically I have a parent container that has padding: 1%. In that container is the hg_graph div that has a width of 100%. So basically, it's width should be 98% of the total screen size. When HighCharts generates the graph, it's getting the full page width and not the width of hg_graph (98%). This only occurs on first page load. If I resize the browser Highcharts automatically re-renders itself into the proper width of 98%.Odeen
R
3

For those using angular and custom-built components, remember to define a dimensioned display in css (such as block or flex) for the host element.

And when the chart container has padding, you might find this indispensable:

html

<chart (load)="saveInstance($event.context)">
...
</chart>

ts

  saveInstance(chartInstance: any) {
    this.chart = chartInstance;
    setTimeout(() => {
      this.chart.reflow();
    }, 0);
  }

Otherwise the chart will bleed past the container on load and get its correct width only at next browser reflow (eg. when you start to resize window).

Ratha answered 29/3, 2017 at 21:23 Comment(2)
Hello I tried this but it gives me following error: [ts] Property 'reflow' does not exist on type 'Chart'.Investment
Haven't followed Highcharts recently, might be that the API changed, cannot really help now, sorry.Ratha
C
2

The best way is to call chart.reflow in render event function documentation;

 Highcharts.stockChart( 'chartContainer', {
 chart: {
  events: {
    render: function() {
      this.reflow();
    }
  },
  zoomType: 'x',
   ...
},

and remember to set min-width to zero and overflow to hidden in chart container.

#chartContainter {
  min-width: 0;
  overflow: hidden;
  }
Carrillo answered 7/10, 2018 at 0:7 Comment(0)
P
1

I just ran into the same problem today - not on mobile, but with a window sized small on first page load. When the page loads, the chart is hidden, then after some selections on the page, we create the chart. We have set a min-width and max-width for the container in css, but not a width.

When the chart is being created, it needs to determine the dimensions to create the SVG . Since the chart is hidden, it cant get the dimensions properly so the code clones the chart container, positions it off-screen and appends it to the body so that it can determine the height/width.

Since the width is not set, the cloned div tries to take as much space as it can - up to the max-width that I had set. The SVG elements are created using that width, but added to the chart container div which currently is smaller (based on the size of the screen). The result is that the chart extends past the container div's boundaries.

After the chart has rendered the first time, the on-screen dimensions are known and the clone function is not called. This means that any window resizes, or reloading of the chart data cause the chart to size correctly.

I got around this initial-load problem by overriding the Highcharts function cloneRenderTo which clones the div to get dimensions:

(function (H) {
    // encapsulated variables
    var ABSOLUTE = 'absolute';

    /**
    * override cloneRenderTo to get the first chart display to fit in a smaller container based on the viewport size
    */
    H.Chart.prototype.cloneRenderTo = function (revert) {
        var clone = this.renderToClone,
            container = this.container;

        // Destroy the clone and bring the container back to the real renderTo div
        if (revert) {
            if (clone) {
                this.renderTo.appendChild(container);
                H.discardElement(clone);
                delete this.renderToClone;
            }

            // Set up the clone
        } else {
            if (container && container.parentNode === this.renderTo) {
                this.renderTo.removeChild(container); // do not clone this
            }
            this.renderToClone = clone = this.renderTo.cloneNode(0);
            H.css(clone, {
                position: ABSOLUTE,
                top: '-9999px',
                display: 'block' // #833
            });
            if (clone.style.setProperty) { // #2631
                clone.style.setProperty('display', 'block', 'important');
            }
            doc.body.appendChild(clone);

            //SA: constrain cloned element to width of parent element
            if (clone.clientWidth > this.renderTo.parentElement.clientWidth){
                clone.style.width = '' + this.renderTo.parentElement.clientWidth + 'px';
            }

            if (container) {
                clone.appendChild(container);
            }
        }
    }

})(Highcharts);

I saved this function in a separate script file that loads after the Highchart.js script has loaded.

Pterosaur answered 8/5, 2017 at 15:6 Comment(0)
G
0

try and encapsulate the highchart generation inside a pageshow event

$(document).on("pageshow", "#hg_graph", function() {...});
Grating answered 5/12, 2013 at 15:30 Comment(0)
C
0

I resolved this problem (for my case) by ensuring that the containing UI elements render before the chart, allowing Highcharts to calculate the correct width.

For example:

Before:

var renderChart = function(){
...
};
renderChart();

After:

var renderChart = function(){
...
};
setTimeout(renderChart, 0);
Communicative answered 24/2, 2016 at 12:39 Comment(0)
A
0

I have been having this issue too, and the .highcharts-container css solution wasn't working for me. I managed to solve it for my case by splitting out an ng-class condition (which was setting different widths for the container div) into separate divs.

eg, this

<div ng-class="condition?'col-12':'col-6'">
    <chart></chart>
</div>

into

<div ng-show="condition" class="col-12">
    <chart></chart>
</div>
<div ng-show="!condition" class="col-6">
    <chart></chart>
</div>

I couldn't really tell you why it worked though. I'm guessing the ng-class takes longer to calculate the container width and so highcharts renders first with an undefined width? Hopefully this helps someone anyway.

Acuna answered 7/6, 2016 at 1:54 Comment(0)
E
0

I also have the same issue in my app where i am using angular and i also using ngCloak directive which i have removed as i don't need it

after doing this my problem is solved.

Ermines answered 21/7, 2016 at 5:16 Comment(0)
P
0

I have just seen that sometimes there are several issues going on at the same time.

If it happens the height exceed the expected heigh:

SCSS style:

.parent_container{

    position:relative;

    .highcharts-container{position: absolute; width:100% !important;height:100% !important;}
}

If the width exceeds the container (bigger than what's supposed to) or does not resize properly to smaller one:

    let element = $("#"+id);
    element.highcharts({...});

    // For some reason it exceeds the div height.
    // Trick done to reflow the graph. 
    setTimeout(()=>{
        element.highcharts().reflow();
    }, 100 );

The last one happened to me when destroying the chart and creating a new one... the new one was coming with width extra size.

Picrotoxin answered 17/8, 2016 at 13:33 Comment(0)
A
0

I have been also bump into this issue. both affected in desktop and mobile view of the chart.

In my case i have a Chart that update the series color depending on min or max.After updating the points, the highcharts width exceeds container div on its first load.

To fix that, what i did is add chart.reflow(); after the update of points.

CODE:

//First declare the chart
var chart = $('#TopPlayer').highcharts();
//Set the min and max
var min = chart.series[0].dataMin; //Top Losser
var max = chart.series[0].dataMax; //Top Winner

for (var i = 0; i < chart.series[0].points.length; i++) {
    if (chart.series[0].points[i].y === max) {
        chart.series[0].points[i].update({
            color: 'GREEN',
        });
    }
    if (chart.series[0].points[i].y === min) {
        chart.series[0].points[i].update({
            color: 'RED',
        });
    }
}

// redraw the chart after updating the points
chart.reflow();

Hope this helps to those who has the same issue like me. :)

Aeriell answered 4/10, 2016 at 9:22 Comment(0)
P
0

Here's a solution that worked for me ! The charts were working fine for a while and then after a feature they started exceeding their container. Turns out it was the defer attribute on the script in the head of my application.

Try removing defer on your javascript tags:

<script defer src="script.js"></script> to <script src="script.js"></script>

Or moving my stylesheet link higher in the head also seemed to fix it but it's a less reliable solution..

Prenotion answered 18/2, 2019 at 15:16 Comment(0)
C
0

This may have been introduced since the OP in 2013, but you should be able to set height with chart.height (https://api.highcharts.com/highcharts/chart.height)

                options: {
                    chart: {
                        type: 'bar',
                        height: window.innerHeight + 'px',
                    },
                    title: {
                        text: 'Top 10 Users',
                    },
                    subtitle: {
                        text: 'by scores',
                    },

This is a web based solution, but I would expect you could cater it to jQuery.mobile

Chucklehead answered 4/6, 2019 at 19:53 Comment(0)
T
0

None of the answers helped me. I dynamically change chart data and the top answer solution ruins the animations and causes a jump in the chart position.

The workaround that I finally came up with was to set some padding for the chart wrapper element (in my case some part of the chart to left was hidden, so I gave some left padding), and then set the chart main element overflow property to visible. It works and the animations are just fine. You may need some experimenting with padding value to get it perfectly displayed.

<div class="chart-wrapper">
   <!-- high charts main element here -->
</div>

and the style

.chart-wrapper{
  padding-left: 20px;
}

.chart-wrapper > div:first-child{
  overflow: visible !important;
}
Towards answered 29/4, 2021 at 19:37 Comment(0)
E
0

reflow() on load event solve my issue

chart: {
    height,
    events: {
      load: function () {
        this.reflow();
      }
    },
  },
Errol answered 12/1, 2024 at 8:45 Comment(1)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewSextuplet
G
-1

for me, I set chart width:

$('#container').highcharts({
    chart: {
        backgroundColor: 'white',
        **width:3000**,
        ..... }

and in html set overflow:auto

<div id="container" style="**width:100%;overflow:auto**;" ></div>
Gnawing answered 16/10, 2016 at 6:10 Comment(0)
D
-1

I struggled with this for way too long, and found a solution that works for me. A little bit of background on my setup:

  1. The highcharts chart was loading on a tab on my website that is not visible upon logging into the site.
  2. When switching to that tab, the chart was well outside the div.

So, I attached a unique ID to that particular tab, we'll call it tab5, and then bound a click function that forced - and this is the important part - the <svg> element within the container div to 100% using jQuery:

$('#tab5').bind('click', function() {
    $('#container_div svg').width('100%');
});

...and my sanity has been restored. For the moment.

Deplane answered 8/3, 2017 at 17:0 Comment(0)
W
-1

Please add width:100% to chart container.
Hope this will resolve overflow:hidden related issue.

classname{min-height:450px;width: 100%;}
Writeup answered 28/12, 2018 at 9:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.