Learning AMP: Different AMP-AD Units using Media Query — AMPire.city

Alis Monte
2 min readOct 7, 2020
Originally published at https://ampire.city

What Will I Learn?

This tutorial demonstrates how to setup a responsive AMP-AD unit to show different size ads based on screen size via media query.

Requirements:

  • Google AdSense Account;
  • Basic CSS & HTML knowledge;

Working Example

Below you can see a working example of a responsive AMP-AD unit. Note that you have to resize browser size and reload page to see the change.

AMP-AD AdSense Code Example

This is an example of the AMP-AD unit I use myself on all of my blogs. Note that in this article I will not go into ways of implementing the code. If you don’t know how to do it, I recommend reading this article, which goes deeper into setting-up AMP-AD unit code into the blog posts.

<amp-ad 
width="970"
height="90"
media="(min-width: 728px)"
layout="responsive"
type="adsense"
class="adsbygoogle ads_mystyle"
data-ad-format="auto"
data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
data-ad-slot="xxxxxxxxxxxxx">
</amp-ad>
<amp-ad
width="300"
height="250"
media="(max-width: 727px)"
layout="responsive"
type="adsense"
class="adsbygoogle ads_mystyle"
data-ad-format="auto"
data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
data-ad-slot="xxxxxxxxxxxxx">
</amp-ad>

How it Works

As you can see there is a code for two different AMP-AD units. You can use this code straight away, just don’t forget to change data-ad-client and data-ad-slot. The intuitive way to hide, or show, one or another, depending on the screen size would be using CSS. You can do it by assigning different classes to AMP-AD units, but the simplier way would be just to add media query to it. As tou can see it is done on the following line:

... media="(max-width: 727px)" ...

This sets AMP-AD unit to appear on all screens up to 727px wide. You can change it wherever you’d like just as any normal media query. In my given example one of the AMP-AD unites is always visible, but you can use this method to hide it on a desired screens.

This method also makes A/B testing for different size AMP-AD units easy. You can just use AUTO-AMP-ADS instead, but I find it not very viable yet. If you want to learn more about it, you can find more information in this article.

Useful links

Versions
WordPress 5.5.1
AMP 2.0.1

Originally published at https://ampire.city on September 10, 2020.

--

--

Alis Monte

Travel Blogger, Web Designer & AMP Developer | Travel & History Journal: https://www.ctdots.eu | AMP Development & Web Design Tutorials: https://ampire.city