“Object-fit” and “Object-position” — Super CSS

The object-fit and the object-position css property together provide us with the power to manipulate an image or a video and create some magic.

Sandip Shrestha
10 March, 2019 | 2 minutes read
“Object-fit” and “Object-position” — Super CSS

The object-fit CSS property is used to specify how an or should be resized to fit its container and the object-position css property is used together with object-fit to specify how an or should be positioned with x/y coordinates inside its “own content box”. Together they provide us with the power to manipulate an image or a video and create some magic.

Object-fit

This property defines how an image or a video fits inside its content box.

The object-fit property can have the following values:

  • fill(default) – The replaced content is sized to fill the element’s content box. If necessary, the object will be stretched or squished to fit
  • contain – The replaced content is scaled to maintain its aspect ratio while fitting within the element’s content box
  • cover – The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box. The object will be clipped to fit
  • none – The replaced content is not resized
  • scale-down – The content is sized as if none or contain were specified (would result in a smaller concrete object size)

Object-position

The object-position property is used together with object-fit to specify how an <img> or <video> should be positioned with x/y coordinates inside its “own content box”.

The object-position property is used together with object-fit property to move the image around the content box. The default value it takes is object-position: 50% 50%. This is the reason when we apply object-fit: cover the image is positioned in center by default. The x/y coordinates can take a ‘px’ value or a ‘percentage’ value.

img {
	width: 100%;  
    height: 100%;  
    object-fit: none; 
    object-position: 5px 10%; 
 }

The above code resizes an image to fit its content box, and position the image 5px from the left and 10% from the top inside the content box.

Apart from providing x/y coordinates values, object-position supports values like ‘bottom’, ‘center’, ‘top’, ‘left’ and ‘right’ which are self-explanatory.

Browser support

object-fit and object-position is supported by all latest version of browser except IE.

Copyright © 2020, Sandip Shrestha. All rights reserved.