For most of my blog posts I need to use two different images for desktop vs mobile. Sometimes it's because of placement issues but it's mostly for promoting my products. I would like to have a wider image on desktop between paragraphs, but a more square shaped image for mobile in the same place so it isn't all squished and hard to read the text in the image.
I have done this using @media queries in my custom CSS template in my WordPress theme (Sprout), and it works fine usually - but not on my amp pages.
@media (min-width: 980px) {
img.beat-pcos-10-week-program-ad-mobile.aligncenter {
display: none;
}
}
@media (max-width: 980px) {
img.beat-pcos-10-week-program-ad-desktop.aligncenter {
display: none;
}
}
For example:
http://www.smartfertilitychoices.com/5-sugar-hacks-dessert-pcos/ vs http://www.smartfertilitychoices.com/5-sugar-hacks-dessert-pcos/amp/
Towards the bottom of the blog post, there is an image promoting my 10 Week Program and using the code above, it shows a different image depending on browser width on the regular post, but not the AMP post.
Is there a way to hide the desktop version of the image on my AMP posts?
Thanks!
I'd strongly advice against using CSS media queries to show or hide images based on device dimensions (for AMP and non-AMP pages). The problem is: even if an image is hidden via display: none
it's still going to be downloaded. This means in your case the user will always have to download both versions of your image which is a waste of bandwidth.
Here are two possible approaches to avoid this for AMP and non-AMP pages:
Non-AMP
For non-AMP pages you can use the picture
element. It allows you to specify different sources for different device dimensions. The browser will only download the image that fits the current device:
<picture>
<source srcset="wide.png" media="(min-width: 980px)">
<img src="square.jpg" alt="...">
</picture>
AMP
AMP doesn't support the picture element, but you can replicate the behavior using element media queries:
<amp-img
media="(max-width: 980px)"
src="square.jpg"
width=400
height=400
layout="responsive">
</amp-img>
<amp-img
media="(min-width: 980px)"
src="wide.jpg"
width=1280
height=768
layout="responsive">
</amp-img>
This will also ensure that only one image will be downloaded.