Member-only story
Vue.js — Making a image component with contain/cover property
Displaying a set of images in a grid is a very common design in a gallery or e-commerce website. Yet, it is usually difficult to fit your photos into your gird, as the height-width ratio of your gird is usually variable. You will have to stretch them. Unfortunately, the default <img> tag doesn’t work very well on stretching.


The problem With <img>
Suppose you have two photos shown above. It is very difficult to stretch them universally that fit both directions using only the default <img> tag.


You can set both width and height to 100%, but it doesn’t look good at all as it doesn’t follow the aspect ratio.

What we want is to fit the image into the layout while keeping the aspect ratio.
Using background-image
One hack here is to use a empty <div> with background-image instead of the <img> tag.

background-size:
contain
background-size:
coverBy setting the “background-size” property, we can have a very well stretched image. However, the drawback of using background-image is it doesn’t work well with SEO and you cannot add “alt” to label your photos for crawlers.
Using “object-fit”
Another workaround is to use the “ object-fit” property of <img> tag. It act exactly the same with “background-size”, which is done in browser level. Yet, not all the browser support this property.