Object-fit
Learn image fitting methods with object-fit.
What is object-fit?
When you fit an img or video into a frame, the default behavior stretches the image and distorts it. The object-fit property controls how the image sits inside the frame.
The two most common values: cover crops the image to fill the frame; contain shows the whole image, leaving gaps when needed. Galleries tend to use cover; product previews often use contain.
Shift the crop with object-position
object-fit: cover crops the image but centers the crop. Sometimes an important face or object falls outside the frame. The object-position property shifts the crop.
You give it a position: center, top, top left, and so on. To keep a face near the top of a portrait, object-position: top is enough.
Exercise Add cover and ratio to a gallery image
Give the .gallery img selector object-fit: cover and aspect-ratio: 4 / 3. Also add width: 100%. The image will crop to fill the frame.
Show example solution
/* gallery image fills the frame */
.gallery img {
object-fit: cover;
aspect-ratio: 4 / 3;
width: 100%;
}
Test yourself
-
Which value shows the entire image?
- cover
- fill
- scale-down
- contain
Show answer
contain — Correct. contain shows the whole image, leaving gaps when needed.
-
Write the object-fit property
.thumb img { ____: cover; width: 100%; height: 100%; }Show answer
.thumb img { object-fit: cover; width: 100%; height: 100%; } -
Match each object-fit value to its meaning
- cover
- Crops to fill
- contain
- Shows the whole image
- fill
- Stretches and distorts
- scale-down
- Picks the smaller size