Responsive Asynchronous Adsense Ads with CSS Media Queries Tutorial

Now that Asynchronous Adsense is here (in beta at least) its time to take a look at how we can use this new ad code and apply it to responsive sites.

Asynchronous Adsense includes inline styling to set the size of the ad. Here’s an example:

<script async src="http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:inline-block;width:300px;height:250px"
     data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
     data-ad-slot="XXXXXXXXXX"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

The code which controls ad size is the style line. The great news is that its possible to remove the style line and style it separately using CSS.

Note: Even though I haven’t seen any announcement from Google of how this should be officially done within the terms of the Adsense TOS, it would seem from the developers blog that this is the intended usage scenario.

The Asynchronous Adsense Script using Media Queries

<style type="text/css">
.adsbygoogle { display:inline-block;width:728px;height:90px;   } 
@media screen and (max-width: 727px)  { .adsbygoogle { display:inline-block;width:468px;height:60px;   } }
@media screen and (max-width: 467px)  { .adsbygoogle { display:inline-block;width:320px;height:50px;   } }
</style>

<script async src="http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
     data-ad-slot="XXXXXXXXXX"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

VIEW DEMO SITE EXAMPLE

As you can see I have removed the inline styling from within the ad code and have instead used media queries to style the adsbygoogle class depending on what the current width of the screen is.

The default styling is for a 728px wide ad, however, if the width of the screen becomes smaller then the media query kicks in and styles it to suit a smaller ad.

Remember that when you try this you will still have to refresh your browser page to see the effect.

CSS styling of Adsense ads opens up some very interesting possibilities. Are you using the new asynchronous Adsense ads yet? If so let me know. I’d love to see how you are experimenting with them.

Enjoyed this post? Share it!