Emmanuel Akinfulubi

HTML and CSSPractical I

object-fit: cover to keep image proportions in CSS

5 Keep an image in proportion inside a fixed box

easy

Fit an image into a box of a set size without squashing it. Fill the box, cropping whatever does not fit.

Stuck? Three hints, smallest first
  1. 1. object-fit: cover fills the box and crops; contain fits it all in and leaves gaps.
  2. 2. The image needs width and height set to the box, or object-fit has nothing to work against.
  3. 3. object-position decides which part survives the crop.

index.html

<div class="thumb">
  <img
    alt="A solid colour standing in for a photograph"
    width="300" height="200"
    src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='200'%3E%3Crect width='300' height='200' fill='%233055d8'/%3E%3Ccircle cx='60' cy='60' r='40' fill='%23ffd75e'/%3E%3C/svg%3E">
</div>

style.css

.thumb {
  width: 160px;
  height: 160px;
  overflow: hidden;
  border-radius: 8px;
}

.thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;          /* fill the box, crop the overflow */
  object-position: top left;  /* and keep this corner when cropping */
  display: block;
}
Rendered result. Shown, not machine-checked: there is no browser in the build.
8 checks that prove this answer

Assertions, run in the browser. The markup and styles above are handed to them as html and css, so press Run and each check prints ok. The build fails if a single one fails.

Checks for exercise 5

test('the image fills and crops', declares(css, 'object-fit', 'cover'), true);
test('which part survives is chosen', /object-position\s*:/.test(css), true);
test('the image is sized to its box', /width\s*:\s*100%/.test(css), true);
test('and given a height too', /height\s*:\s*100%/.test(css), true);
test('display block removes the inline gap below it', declares(css, 'display', 'block'), true);
test('the image has alternative text', hasAttr(html, 'alt'), true);
test('and intrinsic dimensions, so the layout does not jump', hasAttr(html, 'width') && hasAttr(html, 'height'), true);
test('the source is inline, so this page needs no network', /^<div/.test(html.trim()) && /data:image/.test(html), true);

Output


      

Three details beyond object-fit. The alt attribute is not optional — a decorative image takes alt="", never nothing at all. The width and height attributes let the browser reserve space before the image loads, which is what stops the page jumping. And display: block removes the few pixels of space an inline image leaves underneath it, which is the cause of most "why is there a gap" questions.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.