Since I've implemented Google AMP I am struggling with this problem. Every time I add an image with a width
far smaller than my website width
, amp-img
automatically add margins to keep the aspect ratio, like this:
I have tried other layouts mentioned in the [official documentation],(https://www.ampproject.org/docs/guides/responsive/control_layout#supported-values-for-the-layout-attribute) like flex-item
.
With flex-item
for example, I can get the desired behavior in the desktop version, that is, reducing the total margin of the image to look like this:
But in the mobile version, when an image is wider that the screen, the image overflows left and right.
Is there a way I can tweek the responsive layout
in order to remove such larger margins when the image is relative small?
Investigating a bit in the code, the problem seems to be caused by the element i-amphtml-sizer
, which is an element google-amp adds automatically and of which I have no control of.
I am not posting the url for my blog post in case it is considered spam, but if for some reason you need it, I'll update the question.
It seems more people are having this issue.
I solved it! reading amp documentation on github, in concrete the section on amp-html-layout
, in "sizes" there is an example saying:
In the following example, if the viewport is wider than 320px, the image will be 320px wide, otherwise, it will be 100vw wide (100% of the viewport width).
<amp-img src="https://acme.org/image1.png"
width="400" height="300"
layout="responsive"
sizes="(min-width: 320px) 320px, 100vw">
</amp-img>
Previously, my image was:
<figure>
<amp-img
on="tap:lightbox1"
role="button"
tabindex="0"
layout="responsive" src="/img/securitynow.jpg"
width="100"
height="100">
</amp-img>
</figure>
After reading AMP documentation:
<figure>
<amp-img
sizes="(min-width: 100px) 100px, 100vw"
on="tap:lightbox1"
role="button"
tabindex="0"
layout="responsive" src="/img/securitynow.jpg"
width="100"
height="100">
</amp-img>
</figure>
Now it is displaying well on all screen sizes:
In order to work with all kind of image sizes, I'm following this rule:
sizes="(min-width: withOfImage) WithOfImage, 100vw"
This way, when the screen is wider than the image width, the image will have its original width, otherwise the image will be 100%
of the viewport width.