ScreenshotNeo

BlogHow-to

CSS object-fit: How to Fit Images in Their Containers

Use CSS object-fit to fit images without stretching. Compare all five values, size the image box, and control cropping with object-position.

By the ScreenshotNeo team4 October 20269 min read

To fit an image without stretching it, give the image element a definite width and height, then choose object-fit: contain to show the whole image or object-fit: cover to fill the box and crop any excess. Use object-position to move the crop toward the subject. Avoid the default fill when the source and box have different aspect ratios and distortion is not acceptable.

Choose the right object-fit value

object-fit controls how an image or other replaced element’s content is drawn inside that element’s content box. It does not size the element itself. The property is not inherited, and its initial value is fill. The CSS Images specification defines five values:

Value Result Use it when
cover Preserves the source aspect ratio and fills the box. Excess content is clipped if the ratios differ. A card, thumbnail, or frame must be filled edge to edge and cropping is acceptable.
contain Preserves the source ratio and fits the whole image inside the box. Unused space remains. The complete logo, diagram, or product image must stay visible.
fill Fills the box, stretching the content when its ratio differs. Distortion is acceptable or the source already has the box’s ratio.
none Leaves the content at its natural size, even when it overflows or does not fill the box. You want the intrinsic object size rather than fitting or scaling.
scale-down Chooses the smaller result of none and contain. The image may shrink to fit but should not be enlarged beyond the smaller outcome.

In short: use cover for full frames, contain for complete visibility, and scale-down when the image should never be enlarged. The specification describes the sizing behavior; MDN documents the visible outcomes, including clipping with cover and empty space with contain. See the CSS Images specification and MDN’s object-fit reference.

Set the image box first

The element needs a useful box for object-fit to work inside. For a card with a fixed-height image area:

<article class="card">
  <img class="card-image" src="photo.jpg" alt="A mountain reflected in a lake">
  <h2>Mountain lake</h2>
</article>
.card-image {
  display: block;
  width: 100%;
  height: 12rem;
  object-fit: cover;
  object-position: center;
}

Here the element fills the card’s available width and has a fixed height. cover preserves the photograph’s proportions while clipping the edges needed to fill that box. Change to contain when the entire image matters; the element’s background will show through any unfilled area.

If you set only one dimension, the browser normally calculates the other from the image’s intrinsic aspect ratio. Setting both width and height can give the element a different ratio from its source. With the default fill, the content may then look distorted. See MDN’s object-fit documentation for the distinction between the element box and the media rendered within it.

Control the visible crop with object-position

object-position aligns the image content inside its element box. Its default is centered. With cover, adjust it when the centered crop cuts off a face, product, or other focal point:

.hero-image {
  display: block;
  width: 100%;
  height: 24rem;
  object-fit: cover;
  object-position: 60% 30%;
}

That percentage pair changes the alignment of the image within the frame. You can also use keywords such as top or right, or percentage and length positions. Inspect the actual source and target frame to choose a useful position; there is no one crop coordinate that works for every image. object-position also affects alignment when contain leaves empty space. Read MDN’s object-position reference.

Complete runnable example

Save this as object-fit.html and open it in a browser. The two frames use the same image so you can compare a full image with a cropped fill. Replace the image URL with your own asset when adapting the example.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Compare object-fit values</title>
  <style>
    * { box-sizing: border-box; }
    body {
      margin: 2rem auto;
      max-width: 56rem;
      padding: 0 1rem;
      font: 1rem/1.5 system-ui, sans-serif;
      color: #1b2430;
    }
    .examples {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
      gap: 1rem;
    }
    figure { margin: 0; }
    figure img {
      display: block;
      width: 100%;
      height: 13rem;
      background: #e8edf2;
      border: 1px solid #cbd3dc;
    }
    .cover { object-fit: cover; object-position: center; }
    .contain { object-fit: contain; }
    figcaption { margin-top: .5rem; }
  </style>
</head>
<body>
  <h1>Fit images inside a frame</h1>
  <div class="examples">
    <figure>
      <img class="cover" src="https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?w=1200" alt="Landscape with a wide view">
      <figcaption>Cover: fills the frame and may crop.</figcaption>
    </figure>
    <figure>
      <img class="contain" src="https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?w=1200" alt="The same landscape fitted in full">
      <figcaption>Contain: shows the whole image and may leave space.</figcaption>
    </figure>
  </div>
</body>
</html>

The example uses external image hosting, so an offline browser or network restriction may prevent it from loading. For a self-contained local test, download an image you are allowed to use and replace both src values with its local path.

Common patterns and edge cases

Responsive cards and thumbnails

A fixed height is straightforward, but a consistent aspect ratio often adapts better across widths:

.thumbnail {
  display: block;
  width: 100%;
  aspect-ratio: 4 / 3;
  object-fit: cover;
}

The aspect ratio helps establish the element’s frame. Check the rendered box in the target layout if other CSS constraints affect its dimensions.

Logos, diagrams, and product images

Use contain when clipping would hide required details. Give the frame a background if the remaining space should be visually distinct:

.product-image {
  display: block;
  width: 100%;
  height: 18rem;
  padding: 1rem;
  background: #f3f5f7;
  object-fit: contain;
}

Small images that should not be enlarged

Use scale-down to select the smaller of natural-size rendering and contained rendering. This is useful when upscaling would make a small asset look soft, while still allowing a large image to shrink into its box.

Images that must remain uncropped and uncrowded

none keeps the content at its natural size. If it is larger than the box, overflow behavior depends on the surrounding layout and element styling; none itself does not resize it to fit.

When object-fit has no effect

The property applies to replaced elements such as <img> and <video>. It is not a general sizing property for arbitrary HTML boxes. MDN states that it has no effect on <iframe>, <embed>, or <fencedframe>. For an iframe, size and position the iframe element itself or use a different embedding approach. See MDN’s compatibility and scope notes.

Accessibility and meaningful cropping

Keep useful alternative text on informative images. CSS cropping changes what is visible, so check that a crop does not hide information a user needs. If the full asset conveys essential details, use contain or provide the information in text as well.

Browser support and implementation notes

MDN marks object-fit as Baseline Widely available. Its reference notes that the formal grammar reflects a newer standard and that browser support may vary for newer syntax. The established values shown here are broadly supported; check the compatibility data if using newer grammar. See MDN browser compatibility data.

Test the actual target browsers and image ratios, especially where the crop is part of the design. The relevant variables are the source dimensions, rendered element box, fit value, and position.

Troubleshooting

Symptom Likely cause Fix
The image looks stretched or squashed. The element has both dimensions constrained and uses the default fill. Choose cover if cropping is acceptable or contain if the entire image must show.
The image does not fill the frame. The element itself may not have the intended dimensions, or contain is leaving space by design. Inspect the image element’s computed width and height. Set the frame dimensions; switch to cover only if cropping is acceptable.
A face or object disappears. cover crops to fill the box, with centered positioning by default. Adjust object-position, or use contain if all content must remain visible.
There are bars or empty areas around the image. contain preserves the ratio and leaves the unused part of the box uncovered. Set a suitable background on the image element or its frame, or choose cover if a crop is acceptable.
Changing object-fit does nothing. The target may not be a supported replaced element, or the visible issue may be element sizing rather than content fitting. Use it on an <img> or <video>, then inspect the element box. It does not affect iframes, embeds, or fenced frames according to MDN.
The image is unexpectedly tiny or huge. none, scale-down, intrinsic dimensions, or a missing box constraint may be determining the result. Check the selected value and computed box size. Set dimensions intentionally, then choose the fit behavior required by the design.
A CSS change does not appear in the page. A later or more specific rule may override the declaration, or the image has not loaded. Inspect computed styles and network loading in developer tools; confirm the rule applies to the image element and the source URL succeeds.

Performance, reliability, and cost

object-fit is a browser presentation rule. For ordinary page use it does not require a separate image service or a build step. It also does not change the source file or reduce the bytes downloaded: if transfer size matters, serve appropriately sized and compressed image assets separately. Reserve layout space with dimensions or an aspect ratio to reduce layout shifts while images load.

Reliability depends on the image URL loading and the chosen box and crop remaining suitable at the sizes you support. Test portrait, landscape, and unusually wide or tall sources, and inspect the focal point at narrow layouts. There is no API cost for applying this CSS; the relevant costs are your normal asset hosting and transfer costs.

Or skip the browser setup

If you need a screenshot of the rendered page to check how the crop looks, ScreenshotNeo is a website screenshot API and MCP server. It can capture a page after your CSS is applied. The API accepts one GET request for a screenshot or PDF; see the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners are accepted and removed before capture, along with supported newsletter popups and chat widgets. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; response headers report the page verdict and billing status. Its MCP server provides screenshot tools for AI agents. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. You can sign up free for 1,000 screenshots a month, with no card.

FAQ

Does object-fit work on a background image?

No. It controls content inside replaced elements such as <img> and <video>. For a CSS background image, use background sizing and positioning properties instead.

Which value preserves the whole image?

contain preserves the complete image inside the box, potentially leaving uncovered space.

Which value fills a frame without distortion?

cover preserves the image’s ratio and fills the frame, cropping content when the ratios differ.

Can object-fit change the image file’s dimensions?

No. It changes how the object is rendered inside the element box. It does not edit or resize the source asset.