Search code examples
carouselamp-html

"Position: Contain" in AMP Carousel


When creating an AMP Carousel, how do I make sure that pictures with different proportions stay contained in the same way? In other words, the pictures will display width: 100%, but the height will be cut in relation to the proportion of the picture.


Solution

  • You can achieve this combining a fixed-height layout for the amp-carousel with a fill layout for the amp-img:

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

    The trick is to use object-fit: contain|cover for the embedded img:

    .contain img {
      object-fit: cover;
    }
    

    Here is a sample.