Understanding the object-fit
Property
The object-fit
property specifies how the content of a replaced element (like an <img>
or <video>
) should be resized to fit its container.
contain
: Scales the content to fit within the container while maintaining the aspect ratio, possibly leaving some empty space.
CSS
x
.contain {
object-fit: contain;
}
cover
: Scales the content to cover the container while maintaining the aspect ratio, cropping if necessary.
CSS
.cover {
object-fit: cover;
}
fill
: Stretches the content to fill the container, which may distort the aspect ratio.
CSS
.fill {
object-fit: fill;
}
none
: Keeps the original size of the content, potentially causing overflow.
CSS
.none {
object-fit: none;
}
scale-down
: Scales down the content to fit within the container, similar tocontain
, but only if it’s larger.
CSS
.scale-down {
object-fit: scale-down;
}
CSS Object Fit Example Code
CSS
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Object Fit Example</title>
<style>
.container {
width: 300px;
height: 200px;
border: 2px solid black;
margin-bottom: 20px;
}
.contain {
object-fit: contain;
}
.cover {
object-fit: cover;
}
.fill {
object-fit: fill;
}
.none {
object-fit: none;
}
.scale-down {
object-fit: scale-down;
}
</style>
</head>
<body>
<div class="container">
<img src="example.jpg" alt="Example Image" class="contain">
</div>
<div class="container">
<img src="example.jpg" alt="Example Image" class="cover">
</div>
<div class="container">
<img src="example.jpg" alt="Example Image" class="fill">
</div>
<div class="container">
<img src="example.jpg" alt="Example Image" class="none">
</div>
<div class="container">
<img src="example.jpg" alt="Example Image" class="scale-down">
</div>
</body>
</html>
