7

I'm currently in the process of making my website AMP-ified my site is built in bootstrap and everything is responsive so most of my images I just set like so:

img{
  width:100%;
  height:auto;
}

However the problem im running into with my amp-img is that it requires a width and height to be set on the image. What is the correct way of making responsive images with amp is there anyway to do this without setting height and width?

Sanchit Gupta
  • 3,148
  • 2
  • 28
  • 36
NooBskie
  • 3,761
  • 31
  • 51

3 Answers3

2

Without knowing the width or height of your image the only way to show your image is to give it the layout attribute fill and wrap it in a element with add which has the following css property object-fit set to contain.

.ampImg__Wrapper {
  object-fit: contain;
}
Stefan Kunze
  • 618
  • 4
  • 14
1

An amp requires the dimensions to be in the tag for a reason

The size you put in there is the size the amp-script uses to generate a placeholder. The placeholder stops the content from jumping around while the images load.

That being said, just put the organic image dimensions in the tag and use the two following properties in your CSS to make sure images play nice

(make sure you add a selector of-course)

{
  max-width: 100%;
  height: auto;
}
1

The AMP way to achieve that is by using the layout attribute. In amp-img, you specify the source, the native height and weight ; sourceset with formats, in "css pixels"(e.g. 96px/in) for your responsive image with layout= responsive and you're done. AMP will maintain the h/w ratio.

Ex.

<amp-img
    src="/img/small.jpg"
    srcset="/img/medium.jpg 640w,
           /img/small.jpg 320w"
    width="1800"
    height="2777"
    layout="responsive"
    alt="Don't forget to add one">
</amp-img>

In this example, the layout="responsive" would be inferred by the AMP engine because image size and formats are specified. When height and width are not defined, the default layout is "container" (e.g. like plain div).

You can also include amp media queries in amp-img. The preceding example could be set like this:

<amp-img
    media="(max-width: 639px)"
    src="/img/small.jpg"
    width="450"
    height="694"
    layout="responsive"
    alt="Don't forget to add one">
</amp-img>
<amp-img
    media="(min-width: 639px)"
    src="/img/medium.jpg"
    width="900"
    height="1388"
    layout="responsive"
    alt="Don't forget to add one">
</amp-img>

In this case, the "media" attribute will have precedence over the adaptative selection (but it makes almost no practical differences except if you want to force a certain image upon a certain screen size).

For a good overview: https://www.ampbyexample.com/advanced/layout_system/

Hope this help

bFavreault
  • 29
  • 4