Friday, October 12, 2012

Adsense - Responsive Ads with CSS @media queries from Bootstrap responsive utility classes

Adsense - Responsive Ads with Bootstrap and CSS @media queries


Twitter Bootstrap is built with Responsive utility classes that help us to implement different sizes of ads   for different devices.

ClassPhones767px and belowTablets979px to 768pxDesktopsDefault
.visible-phoneVisible
.visible-tabletVisible
.visible-desktopVisible
.hidden-phoneVisibleVisible
.hidden-tabletVisibleVisible
.hidden-desktopVisibleVisible
So, the idea is to use these classes to show the right ads. In my case I have the following set:

  • Desktop
    • Leaderboard (728x90)


  • Portrait tablet to landscape and desktop
    • Banner (468x60)

  • Landscape phone to portrait tablet
    • Banner (468x60)

  • Landscape phones and down
    • Half Banner (234x60)


It is really simple to achieve this using the Bootstrap built-in responsive utility classes. See the example bellow:


 <div class="visible-desktop">  
        <script type="text/javascript">  
             google_ad_client = "ca-pub-XXXXXX";  
             google_ad_slot = "XXXXXXX";  
             google_ad_width = 728;  
             google_ad_height = 90;  
        </script>  
        <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>   
 </div>  

 <div class="visible-tablet">  
        <script type="text/javascript">  
             google_ad_client = "ca-pub-XXXXXX";  
             google_ad_slot = "XXXXXXX";  
             google_ad_width = 468;  
             google_ad_height = 60;  
        </script>  
        <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
 </div>  

 <div class="visible-phone">  
        <script type="text/javascript">  
             google_ad_client = "ca-pub-XXXXXX";  
             google_ad_slot = "XXXXXXX";  
             google_ad_width = 234;  
             google_ad_height = 60;  
        </script>  
        <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
 </div>  

Easy uh?!

Here is a example showing how we can make the same thing using Javascript only.



1 comment: