The CSS object-fit property dictates how an <img> or <video> should be resized to fit its container.
This property instructs the content to occupy the container in different manners, such as preserving the aspect ratio or stretching to utilize maximum space.
Consider the following image of Paris. It has a width of 400 pixels and a height of 300 pixels.
However, if we adjust the styling of the image mentioned earlier to be half its original width (200 pixels) while maintaining its height (300 pixels), it will appear as follows:
Example
img { width: 200px; height: 300px; } |
We observe that the image is being compressed to accommodate the container size of 200×300 pixels, resulting in the destruction of its original aspect ratio.
This is where the object-fit property becomes useful. The object-fit property offers several values:
When employing object-fit: cover; the image maintains its aspect ratio and occupies the specified dimensions. However, the image may be clipped to fit entirely within the container.
Example
img { width: 200px; height: 300px; object-fit: cover; } |
When utilizing object-fit: contain; the image preserves its aspect ratio while being resized to fit within the specified dimensions.
Example
img { width: 200px; height: 300px; object-fit: contain; } |
When utilizing object-fit: fill; the image is adjusted to completely occupy the specified dimensions. If needed, the image will be either stretched or compressed to fit accordingly.
Example
img { |
When employing object-fit: none; the image retains its original size without any resizing.
Example
img { width: 200px; height: 300px; object-fit: cover; } |
When object-fit: scale-down; is applied, the image is adjusted to a size that is either its original size or the size specified by the contain property, whichever is smaller.
Example
img { |
However, without utilizing object-fit, resizing the browser window may distort the aspect ratio of the images.
Example
In the subsequent example, we apply object-fit: cover;, ensuring that when we resize the browser window, the aspect ratio of the images remains intact.
Example
The forthcoming example showcases a demonstration encompassing all conceivable values of the object-fit property.
Example
.fill {object-fit: fill;} |