CSS
🎯 CSS object-fit Property
The object-fit CSS property defines how an image or video should fit inside its container. It controls whether the media is stretched, cropped, or scaled to match the box dimensions.
In simple terms, object-fit answers the question: “How should this image behave inside its container?”
🔹 Why Use object-fit?
-
Key Benefits
- Controls image and video scaling behavior.
- Prevents unwanted stretching.
- Improves responsive image layouts.
- Essential for modern UI design (cards, galleries, banners).
🧩 Basic Usage
img {
object-fit: cover;
}
🔹 object-fit Values
1️⃣ fill (Default)
The image stretches to fill the entire container. This may cause distortion.
img {
object-fit: fill;
}
2️⃣ cover
The image covers the container completely while maintaining aspect ratio. Overflow is cropped.
img {
object-fit: cover;
}
3️⃣ contain
The entire image is visible, but empty space may appear inside the container.
img {
object-fit: contain;
}
4️⃣ none
The image keeps its original size and is not resized.
img {
object-fit: none;
}
5️⃣ scale-down
Automatically chooses between contain and none depending on which fits better.
img {
object-fit: scale-down;
}
6️⃣ initial
Resets the property to its default value, which is fill.
img {
object-fit: initial;
}
-
📊 Quick Comparison
- fill → Stretches image (may distort)
- cover → Fills container, crops overflow
- contain → Shows full image, may leave space
- none → Keeps original size
- scale-down → Automatically chooses best fit
-
🧠 Summary
- object-fit controls how media fits inside a container.
- cover is the most commonly used value in modern design.
- contain preserves full image visibility.
