CSS - Object-fit & Object-position

Overview

Estimated time: 8–12 minutes

Control how images and videos fit inside fixed boxes without distorting aspect ratios.

Learning Objectives

  • Use object-fit: cover|contain for media cropping vs letterboxing.
  • Adjust framing with object-position.

Details & Examples

img.cover{ width:100%; height:240px; object-fit: cover; object-position: 50% 30%; }
img.contain{ width:100%; height:240px; object-fit: contain; background:#0a0f1a; }

Try it

Common Pitfalls

  • object-fit applies to replaced elements (img, video), not background images.

Checks for Understanding

  1. Which setting crops to fill the box while preserving aspect ratio?
Show answers
  1. object-fit: cover.

Exercises

  1. Demonstrate object-fit: cover vs contain on the same image frames.
  2. Use object-position to frame the focal point of an image toward the top-left.
Suggested answers
  1. Create two elements with fixed dimensions and apply the two settings to compare.
  2. object-position: 20% 10%; or similar to bias the crop.