How to use the object-fit Property In CSS

  • The object-fit property works with images and videos, ensuring they fit within their container without distortion.
  • Create the basic structure of the web page using `<img>` and `<video>` elements in the HTML document file.
  • Apply the `object-fit` property to the media elements.

Example: To demonstrate maintaining the aspect ratio of an element using the css object-fit property.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0">
  <title>Object Fit Property</title>
  <style>
    .image {
      width: 100%;
      height: auto;
      object-fit: cover;
    }
  </style>
</head>
<body>
  <img src=
"https://media.w3wiki.org/wp-content/uploads/20240522090341/Aspect-ratio-16x9svg.png" 
       class="image" 
       alt="Responsive Image">
</body>
</html>

Output:

The image or video will scale to fit the container while maintaining its aspect ratio.



How to Maintain the Aspect Ratio of an Element using CSS?

Maintaining the aspect ratio of an element ensures that the element retains its width-to-height proportion regardless of screen size or resizing. This is particularly useful for responsive web design, where you need images, videos, and other elements to scale correctly without distortion.

There are several approaches to maintaining the aspect ratio of an element using CSS which are as follows:

Table of Content

  • Using the Padding Technique
  • Using the aspect-ratio Property
  • Using the object-fit Property

Similar Reads

Using the Padding Technique

The padding technique leverages the fact that padding percentages in CSS are based on the width of the containing block, allowing you to create a box that scales with a fixed aspect ratio.Create the basic structure of the web page using `

Using the aspect-ratio Property

The CSS aspect-ratio property directly specifies the aspect ratio of an element, making it the simplest method.Create the basic structure of the web page using a `

Using the object-fit Property

The object-fit property works with images and videos, ensuring they fit within their container without distortion.Create the basic structure of the web page using `` and `