CSS object-fit Property

You are Here:

CSS object-fit Property

CSS object-fit property specifies how an <img> or <video> should be resized to fit its container.

Example

HTML Online Editor
<!DOCTYPE html> <html lang="en-US"> <head> <style> img{ width: 250px; height: 150px; border: 1px solid #000; } #myFill img{ object-fit: fill; } #myContain img{ object-fit: contain; } #myCover img{ object-fit: cover; } #myNone img{ object-fit: none; } #myScaleDown img{ object-fit: scale-down; } </style> </head> <body> <h1>CSS object-fit Property</h1> <h2>object-fit: fill;</h2> <div id="myFill"> <img src="devices.jpg"> </div> <h2>object-fit: contain;</h2> <div id="myContain"> <img src="devices.jpg"> </div> <h2>object-fit: cover;</h2> <div id="myCover"> <img src="devices.jpg"> </div> <h2>object-fit: none;</h2> <div id="myNone"> <img src="devices.jpg"> </div> <h2>object-fit: scale-down;</h2> <div id="myScaleDown"> <img src="devices.jpg"> </div> </body> </html>

Syntax

Using CSS

element{ object-fit: cover; }

Using Javascript

object.style.objectFit="cover";

Animatable

No, object-fit property is not animatable. CSS Animatable Properties Reference.

Default Value

Default value for CSS object-fit property is fill.

Property Value

The following table provides a list of values for CSS object-fit property.

ValueExplanation
fillThe replaced content is sized to fill the element’s content box. The entire object will completely fill the box.
containThe replaced content is scaled to maintain its aspect ratio while fitting within the element's content box.
coverThe replaced content is sized to maintain its aspect ratio while filling the element's entire content box. The object will be clipped to fit.
noneThe replaced content is not resized.
scale-downThe content is sized as if none or contain were specified, whichever would result in a smaller concrete object size.

Using JavaScript

In the following example, we will demonstrate how to change the CSS object-fit property of an element using JavaScript.

Example

HTML Online Editor
<!DOCTYPE html> <html lang="en-US"> <head> <style> img{ width: 250px; height: 150px; border: 1px solid #000; object-fit: fill; } </style> </head> <body> <h1>CSS object-fit Property</h1> <div> <img src="devices.jpg"> </div> <button onclick="myFunction()">Click Me</button> <script> var x = document.getElementsByTagName("img")[0]; function myFunction(){ x.style.objectFit = "none"; } </script> </body> </html>

Reminder

Hi Developers, we almost covered 98.7% of CSS Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in CSS.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author