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

--

--

Liu Ting Chun

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