How to modify Google AdSense responsive ad code for device targeting?

In some cases, you may not want to show AdSense ads on certain devices. For example, if an ad unit is placed on the sidebar and is targeted to all devices, it will generally have higher viewability on desktop, while on mobile devices it will appear at the bottom of the page after the main content and, on the contrary, it will have a very low viewability. As a result, the overall viewability of the ad unit will be also quite low. The best way to check this is to build a report in your AdSense account going to Reports > Break down by: Ad unit > then: Platform.

screenshot_12.png

In this case, it is better to leave this ad unit desktop-only and create a new one to be mobile-only, placing it in a more visible position. For other tips on optimizing viewability and why it's important, check out this article.

In order to hide an ad unit based on device, you need to set a parameter with CSS media queries so that no ad request is made and no ad is shown.

The examples described below are acceptable modifications of the AdSense ad code. Find more details here.

Hiding an ad unit on mobile devices

This example shows how to make changes to the AdSense ad code for an ad unit so that it only appears on desktop devices with screen widths greater than 900 pixels.

<style type="text/css">
@media (max-width: 900px) { .banner_only_desktop { display: none; } }
</style>
<ins class="adsbygoogle .banner_only_desktop"
   data-ad-client="ca-pub-XXXXXXX11XXX"
   data-ad-slot="12345678"></ins>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXX11XXX" crossorigin="anonymous"></script>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>

You can adapt this example code for your own site. Please replace:

  • ca-pub-XXXXXXX11XXX with your own publisher ID
  • 12345678 with your own ad unit's ID
  • optionally, all instances of .banner_only_desktop with a unique name, e.g., Home_Page, front_page_123, etc.
Hiding an ad unit on desktop devices

This example shows how to make changes to the AdSense ad code for an ad unit so that it only appears on mobile and tablet devices with screen widths less than 900 pixels.

<style type="text/css">
@media (min-width: 900px) { .banner_only_mobile { display: none; } }
</style>
<ins class="adsbygoogle .banner_only_mobile"
   data-ad-client="ca-pub-XXXXXXX11XXX"
   data-ad-slot="12345678"></ins>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXX11XXX" crossorigin="anonymous"></script>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>

You can adapt this example code for your own site. Please replace:

  • ca-pub-XXXXXXX11XXX with your own publisher ID
  • 12345678 with your own ad unit's ID
  • optionally, all instances of .banner_only_mobile with a unique name, e.g., Home_Page, front_page_123, etc.