01. Modern Features (object-fit, object-position, aspect-ratio, Scroll Snap)
🟡 Intermediate
1. Definition
object-fit: cover scales images proportionally inside aspect containers without distortion. aspect-ratio: 16 / 9 preserves container ratios, and CSS Scroll Snap aligns touch carousels.
2. Why It Is Used
Modern features eliminate image distortion bugs, replace aspect-ratio padding hacks, and create native touch-friendly horizontal carousels without JavaScript libraries.
3. How It Works
object-fit: cover crops an <img> element to fill its container while preserving aspect ratio. scroll-snap-type: x mandatory forces touch swipes to snap to scroll-snap-align: center coordinates.
4. Syntax
.avatar-img {
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
.carousel {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
}
.carousel-item {
scroll-snap-align: start;
}
5. Object Fit Options Reference Table
| Value | Behavior |
|---|---|
fill | Default; stretches image to fit box (distorts ratio) |
contain | Scales image to fit completely inside box without cropping |
cover | Fills box completely (crops edges to preserve ratio) |
none | Ignores box dimensions; retains original image pixel size |
6. Beginner Example
.hero-photo {
width: 100%;
height: 400px;
object-fit: cover;
}
7. Intermediate Example
.video-card {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
border-radius: 12px;
}
8. Advanced Touch Carousel Scroll Snap Example
.slider {
display: flex;
gap: 16px;
overflow-x: auto;
scroll-snap-type: x mandatory;
scroll-behavior: smooth;
padding: 16px 0;
}
.slider-card {
flex: 0 0 80%;
scroll-snap-align: center;
border-radius: 12px;
}
9. Line-by-Line Code Explanation
scroll-snap-type: x mandatory;: Forces horizontal scroll containers to snap cleanly to childscroll-snap-align: centercard boundaries upon user release.
10. Expected Terminal / Browser Output
A native touch-friendly horizontal card carousel that snaps smoothly to each card during swipes.
11. Common Mistakes & Pitfalls
- Setting
object-fitwithout declaring width and height:object-fithas no effect unless explicit box dimensions (width & height) are defined on the image.
12. Important Rules & Limitations
aspect-ratioworks seamlessly across all modern evergreen browsers.
13. Multilingual Explanation: English
object-fit: cover prevents image distortion, while CSS Scroll Snap creates native smooth swiping carousels.
14. Multilingual Explanation: Hindi (Roman Script)
Image stretch hone se bachane ke liye object-fit: cover ka istemaal karein. Touch carousel ke liye CSS Scroll Snap best hai.
15. Multilingual Explanation: Marathi (Roman Script)
Images distort hou n denyasathi object-fit: cover vapara. Carousel sathi CSS Scroll Snap vapara.
16. Practice Questions
- Why does
object-fitrequire fixed box dimensions to function?
17. Practical Coding Challenge
Build a .photo-gallery card using aspect-ratio: 4 / 3 and object-fit: cover.