Responsive Adsense Ads Sized to Enclosing container Element

Edit: this post has been somewhat superseded by new features added to to the Google Adsense responsive ad unit .

In July, Google Adsense finally announced some initial support for responsive web sites. Two problems with the Adsense solution are clear:

  • The ad sizes are controlled via media queries on the viewport size when what is really needed is ad sizes based on the space available in the enclosing HTML container.
  • There's no mechanism to not display an ad. Typically on a smartphone you are not going to want to display as many ads as you will on a desktop or tablet for instance.

The solution I decided to use on is to inject the Adsense ad code with JavaScript based on the width of a DIV element surrounding the ad script. In the example below (apologies for the long wrapped lines), no ad will be displayed if the surrounding element is less that 468px wide, a 468x60 add will be displayed if the width is less than 728px wide and a 728x90 ad is displayed in all other cases.

<div id="ad-home-central" class="ad-wrapper text-align: center;" >
  <script type="text/javascript">
    var width = document.getElementById('ad-home-central').parentNode.clientWidth;

    if (width >= 468 && width <= 727) {
      document.write('<ins class="adsbygoogle" style="display:inline-block;width:468px;height:60px" data-ad-client="ca-pub-xxxxxxxxxxxxxxxx" data-ad-slot="9114431536"></ins>');
      document.write("\x3Cscript>(adsbygoogle = window.adsbygoogle || []).push({});\x3C/script>");

    if (width >= 728 && width <= 10000) {
      document.write('<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-xxxxxxxxxxxxxxxx" data-ad-slot="9114431536"></ins>');
      document.write("\x3Cscript>(adsbygoogle = window.adsbygoogle || []).push({});\x3C/script>");

You also need to add the following code at the bottom of your page for the above example to work.

<script async src=""></script>

The above code is difficult to maintain and impractical if you're inserting the code by hand, but if the code is generated from some server side function then that's not an issue.