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.
<!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:
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