Member-only story

Vue.js — Making a image component with contain/cover property

Liu Ting Chun
3 min readNov 16, 2019

--

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.

By setting width = 100%
By setting height = 100%

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.

By setting width = 100%, height = 100%

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: cover

By 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.

--

--

Liu Ting Chun
Liu Ting Chun

Written by Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.

Responses (1)

Write a response