Responsive `Google Data Studio` Inline Frame Embed Code

Google Data Studio (https://datastudio.google.com/) is a pretty powerful and yet easy to get started with tool to visualize data from a variety of sources (everything from CSV files, to large scale databases). And it lends itself to presenting those graphs in other places on the web and thankfully there is an embed option using the ever popular inline frame (i-frame).

The issue is that the embedded graphs are not responsive and this presents an issue for both mobile phone/tablet screens and websites which might be optimized or designed around responsive elements, such as grids that auto scale to page width etc.

So I used an old CSS trick to fix the aspect ratio to the same aspect ratio as the data studio report in question; in this case 16×9. But the aspect ration can easily be adjusted by modifying the padding-top percentage in the inner frame class below. Simply take the desired aspect ratio as an inverse fraction (9/16 = .5625) and convert it to a percentage. This trick is well known and you can read more about how it works elsewhere on the web just google ‘iframe fixed aspect ratio’ or something to that effect. Some css frameworks even have classes pre-built to add this responsive behavior to i-frames.

There is still an issue with this though and that is that the iframe inner container div will keep its aspect ratio but it will happily overflow bounds and scale indefinitely in vertical/horizontal direction to keep that aspect ratio. So by adding a second wrapping/container div that has a max width you can essentially create a ceiling after which the i-frame will stop scaling up/down creating a responsive frame that scales down when it needs to, retains it’s aspect ratio but won’t keep scaling up infinitely. The second container is really the secret here!

 

The code is below, feel free to play around with it! I hope this helps someone out there trying to embed a google data studio report into another page and needs it to be responsive.

 

<div class="responsive-inline-frame">
  <div class="responsive-inline-frame-inner">
    <!--iframe here-->
  </div>
</div>
.responsive-inline-frame {
  max-width: 800px; /* 800x450 (16x9 aspect ratio) */
  margin: auto;
}
.responsive-inline-frame-inner {
  width: 100%;
  position: relative;
  overflow: hidden;
  padding-top: 56.25%;
  height: 0;
}
.responsive-inline-frame-inner iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

Leave a Reply

Your email address will not be published. Required fields are marked *