Understanding the Object-fit property in CSS

Tram Ho

Object-fit

The CSS object-fit property is used to specify how to resize an <img> or <video> to fit its container.

This attribute indicates the content to fill the container in various ways; such as “keep that aspect ratio” or “expand and take up as much space as possible”.

Look at the following original following image. This image is 400 pixels wide and 300 pixels high:

However, if we style the image above with half the width (200 pixels) and the same height (300 pixels), it will look like this:

As you can see, the aspect ratio of the image has been broken to fit the 200×300 frame.

So we have the attribute Object-fit to solve this problem.

Attribute values Object-fit include :

  • cover – The image keeps its aspect ratio and fills the given size. The image will be cropped to fit.

  • fill – This is the default value. The image is resized to fill the given size. If necessary, the image will be stretched or scaled to fit the frame.

  • contain – The image retains its aspect ratio, but is resized to fit the given dimensions.

  • none – The image is not resized.

Comes with attributes Object-fit we also have attributes Object-position used to position <img> or <video> within its container to help us display the position of the image we want. You can refer to it here https://www.w3schools.com/css/css3_object-position.asp.

Refer :

Share the news now