user3374765
user3374765

Reputation: 31

How to identify desktop or mobile for AMP only site

I am a AMP-HTML newbie trying to create a simple AMP only site and need to identify if the viewing device is high dpi mobile or desktop.

I understand how this can be done with a media query but is there a better/prefered way using AMP specific code?

Am building my knowledge of AMP but have I missed something?

Upvotes: 1

Views: 938

Answers (1)

fstanis
fstanis

Reputation: 5534

Using media queries, as you mention, is the preferred way, but AMP has a few additional features, such as the media attribute on elements, that can make it easier to do this in some circumstances.

This is outlined in Create responsive AMP pages:

In responsive design, you can use CSS @media queries to tailor the styling of your web page for various screen dimensions without having to alter the content of the page. In AMP, you can continue to use those same CSS @media queries. Additionally, for finer control over an AMP element, you can specify the media attribute on the element. This is particularly useful when you need to either show or hide an element based on a media query. See the Changing the art direction of an image section for an example that uses the media attribute.

A simple example of a media attribute is:

<!-- Won't display on screens smaller than 500px -->
<amp-img alt="cat"
  media="(min-width: 500px)"
  width="650"
  height="340"
  src="cat.jpg"></amp-img>

Same can be achieved with CSS:

<style amp-custom>
  @media screen and (max-width: 499px) {
    .catimg {
      display: none;
    }
  }
</style>

[ ... ]

<amp-img alt="cat"
  class="catimg"
  width="650"
  height="340"
  src="cat.jpg"></amp-img>

Upvotes: 1

Related Questions