Lock an Image to a Fixed Aspect Ratio with Percentage-based Padding in Tailwind

Adam Wathan
InstructorAdam Wathan

Share this video with your friends

Send Tweet

Right now the card looks great at this screensize but when that is adjusted (and gets larger) you'll notice that the image resolution will stretch to fit the screen. We will want to respect the original aspect ratio of the image so as the image gets wider, it gets proportionally taller.

To respect the original aspect ratio of the image, we'll need to position the image absolutely in a containing div that has its bottom padding set to a percentage. This will fix that div's aspect ratio which in turn will keep the images aspect ratio fixed as well.

Ronald Rey
Ronald Rey
~ 5 years ago

I pulled this down locally, removed the classes from the image container and the absolute class on the image itself and can see the exact same behavior around the aspect ratio when resizing the viewport. I even tried in IE11 just in case and even then it seems to still work the same way without the padding + absolute positioning hack. In other words, the snippet below...

    <div>
      <img class="h-full w-full object-cover" :src="property.imageUrl" :alt="property.imageAlt">
    </div>

seems to work the same way to me than what you ended up with in the video. What did I miss when testing? Is there an edge case that this workaround accounts for that I didn't come across?

Awesome series by the way, and loving Tailwind! Keep up the good work! <3