CSS object-fit
object-fit decides how the content of a replaced element — an img or video — fits inside its box when the box and content have different aspect ratios.
The five values
| Value | What happens |
|---|---|
fill (default) | Stretch to fill the box — distorts the image. |
contain | Fit inside without cropping. May leave empty bands. |
cover | Fill without distortion. Crops the overhang. |
none | Use the source size — no scaling. |
scale-down | Smaller of none and contain. |
Recipe: square thumbnail from any photo
CSS
.thumb {
width: 120px;
height: 120px;
object-fit: cover; /* crop, never squash */
border-radius: 8px;
}
Recipe: fit a logo without cropping
CSS
.logo-cell {
width: 200px; height: 80px;
}
.logo-cell img {
width: 100%; height: 100%;
object-fit: contain; /* show the whole logo even with bands */
}
Tip: Pair with
object-position if "cover" crops in the wrong place. object-position: top keeps faces in frame.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS object-fit</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Fit the logo entirely inside the box without cropping.
.logo { width: 200px; height: 80px; object-fit:
; }
Opposite of cover — the whole image fits in.
Discussion
Loading…