Nisarg
Nisarg

Reputation: 367

Include image in AMP with correct aspect ratio without knowing height/width

Is there a way to include images in AMP without knowing it's width and height?
I have tried layout=responsive, but it stretches the image as per the given height and width instead of making it responsive.(Original image's aspect ratio is not maintain, instead the given height and width value's aspect ratio is maintained).
I have also tried layout=fill, It maintains aspect ratio but it creates padding if the given height/width is larger than original image's height/width.
If anybody can help me with this problem, as I don't know the dimension of image and want to load it with correct aspect ratio without padding.

Upvotes: 1

Views: 2077

Answers (1)

Sebastian Benz
Sebastian Benz

Reputation: 4288

AMP has a static layout, which means the height of every element must be known in advance. This is why there is no way to embed images with unknown dimensions. There are two workarounds:

1.) Define a fixed height container and let the image fill the available space while maintaining the correct aspect-ratio (this might result in some padding). This is possible by combining layout=fill with the object-fit: contain CSS property.

  .fixed-height-container {
     position: relative;
     width: 100%;
     height: 300px;
   }

  amp-img.contain img {
    object-fit: contain;
  }

  <div class="fixed-height-container">
    <amp-img class="contain"
      layout="fill"
      src="https://unsplash.it/400/300"></amp-img>
  </div>

2.) The other option is to crop the image to fill the available space.

  .fixed-height-container {
     position: relative;
     width: 100%;
     height: 300px;
   }

  amp-img. cover img {
    object-fit: cover;
  }

  <div class="fixed-height-container">
    <amp-img class="cover"
      layout="fill"
      src="https://unsplash.it/400/300"></amp-img>
  </div>

You can find a working sample of the different patterns on ampbyexample.com.

Upvotes: 3

Related Questions