Lesson 50 +10 XP

Object-fit & object-position

object-fit & object-position

Fit images and videos inside a box WITHOUT squishing them. This solves the "picture stretched into a weird shape" problem!

The problem

If you give an image a fixed width and height, it distorts:

img {
  width: 200px;
  height: 200px;   /* image gets squished/stretched */
}

object-fit: cover

Fill the box and CROP the overflow. No distortion. Great for thumbnails:

img {
  width: 200px;
  height: 200px;
  object-fit: cover;   /* crop to fill, keep proportions */
}

object-fit: contain

Fit the WHOLE image inside the box, leaving empty space around it:

img {
  object-fit: contain;   /* the whole image, letterboxed */
}

The rest

ValueBehavior
fillStretch to fill (distorts!). This is the default.
coverFill box, crop overflow.
containWhole image visible, letterboxing.
noneKeep natural size, possibly overflowing.
scale-downSize down instead of up.

object-position

Where the visible part sits when cropping:

img {
  object-fit: cover;
  object-position: left top;        /* keep the left part */
  object-position: 20% 80%;        /* 20% from left, 80% from top */
}

TL;DR

  • object-fit: cover crops to fill; contain shows everything.
  • object-position picks the visible area when cropping.
  • Use on <img>, <video>, <canvas>.
  • Perfect for avatars and thumbnails!