Loading lessons...
Object-fit & object-position
object-fit & object-position
Fit images and videos inside a box WITHOUT squishing them. This solves the "picture stretched into a weird shape" problem!
The problem
If you give an image a fixed width and height, it distorts:
img {
width: 200px;
height: 200px; /* image gets squished/stretched */
}
object-fit: cover
Fill the box and CROP the overflow. No distortion. Great for thumbnails:
img {
width: 200px;
height: 200px;
object-fit: cover; /* crop to fill, keep proportions */
}
object-fit: contain
Fit the WHOLE image inside the box, leaving empty space around it:
img {
object-fit: contain; /* the whole image, letterboxed */
}
The rest
| Value | Behavior |
|---|---|
fill | Stretch to fill (distorts!). This is the default. |
cover | Fill box, crop overflow. |
contain | Whole image visible, letterboxing. |
none | Keep natural size, possibly overflowing. |
scale-down | Size down instead of up. |
object-position
Where the visible part sits when cropping:
img {
object-fit: cover;
object-position: left top; /* keep the left part */
object-position: 20% 80%; /* 20% from left, 80% from top */
}
TL;DR
object-fit: covercrops to fill;containshows everything.object-positionpicks the visible area when cropping.- Use on
<img>,<video>,<canvas>. - Perfect for avatars and thumbnails!