iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS object-fit

object-fit decides how the content of a replaced element — an img or video — fits inside its box when the box and content have different aspect ratios.

The five values

ValueWhat happens
fill (default)Stretch to fill the box — distorts the image.
containFit inside without cropping. May leave empty bands.
coverFill without distortion. Crops the overhang.
noneUse the source size — no scaling.
scale-downSmaller of none and contain.

Recipe: square thumbnail from any photo

CSS
.thumb {
  width: 120px;
  height: 120px;
  object-fit: cover;          /* crop, never squash      */
  border-radius: 8px;
}

Recipe: fit a logo without cropping

CSS
.logo-cell {
  width: 200px; height: 80px;
}
.logo-cell img {
  width: 100%; height: 100%;
  object-fit: contain;        /* show the whole logo even with bands */
}
Tip: Pair with object-position if "cover" crops in the wrong place. object-position: top keeps faces in frame.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS object-fit</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Fit the logo entirely inside the box without cropping.

.logo { width: 200px; height: 80px; object-fit: ; }

Test yourself

Q1. Which value fills the box without distortion (crops if needed)?
Q2. Which value fits the whole image inside (may leave bars)?
Q3. Which is the default value of `object-fit`?

Discussion

Loading…