htmlcssresponsive-imagesgoogle-ampamp-img

Styling responsive layout in amp-img


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:

enter image description here

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:

enter image description here

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.

enter image description here

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.

UPDATE

It seems more people are having this issue.


Solution

  • 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:

    enter image description here

    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.