Knowledge Base

Using CSS to dynamically size map or chart height based on available width

A map or a chart will always try to take up all of the area of its container. Which means that your container needs to be sized in order for the chart/map to even become visible.

Block level elements, such as <div> automatically take up the whole available width.

Unfortunately, that’s not the case with the height. A div will try to dynamically change its height to accommodate its content. Since chart/map container is initially empty, it will have zero height. This in turn means that chart/map will check available space when initializing, which will come out as zero – no map or chart. Or more like zero-height chart. Not good.

For this we usually go and set explicit height of the container. I.e.:

#chartdiv {
  width: 100%;
  height: 400px;

This works, but it will also mean that it will have a constant height, regardless of the available width. The aspect ration will not be kept.

We might utilize CSS media queries to target and override height for specific resolutions, but its an extra work and maintenance.

This demo shows a trick which lets you always keep the height relative to its width using only CSS.

For this we will need to wrap our `chartdiv` into another element, which we will use for sizing:

<div class="chartwrapper">
  <div id="chartdiv" class="chartdiv"></div>

And we will apply the following CSS:

.chartwrapper {
  width: 70%;
  position: relative;
  padding-bottom: 50%;
  box-sizing: border-box;

.chartdiv {
  position: absolute;
  width: 100%;
  height: 100%;

Now, our container will always keep the height relative to the width at 2:1 ratio. The padding-bottom CSS setting defines the ratio.

P.S. you might want to open CodePen demo in a separate window, so you can resize it and check how height changes based on available width.