CHAPTER 59
CSS Object-fit
Learn how object-fit controls how images and videos fit inside their containers.
01. What is CSS Object-fit?
object-fit controls how replaced content such as images fits within a defined box.
cover fills the box while maintaining aspect ratio.
contain keeps the complete image visible.
02. Syntax
img {
width: 300px;
height: 200px;
object-fit: cover;
}
03. Example
CSS / HTML Example
AIFA Coding Lab
<!DOCTYPE html>
<html>
<head>
<style>
.gallery-image {
width: 300px;
height: 200px;
object-fit: cover;
border-radius: 15px;
}
</style>
</head>
<body>
<img
class="gallery-image"
src="https://via.placeholder.com/600x400"
alt="Gallery"
>
</body>
</html>
04. Important Points
✓
cover fills the box and may crop the image.
✓
contain keeps the entire image visible.
✓
fill can distort the image.
✓
Use object-fit for consistent image cards.
05. Common Mistakes
⚠
Using fixed image sizes without object-fit.
⚠
Accidentally cropping important content.
⚠
Forgetting alt text.
06. Real World Use
object-fit is commonly used for product cards, galleries, profile images and blog thumbnails.
Ready to Practice? 🚀
Open the AIFA CSS Editor and practice this chapter live.
Try It Yourself →
Practice Exercise
Create an Image Card
Create a 300x200 image area and use object-fit: cover.