object-fit: cover to keep image proportions in CSS
5 Keep an image in proportion inside a fixed box
easyFit 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.
object-fit: coverfills the box and crops;containfits it all in and leaves gaps. - 2. The image needs
widthandheightset to the box, orobject-fithas nothing to work against. - 3.
object-positiondecides which part survives the crop.
<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>
.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;
}
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.
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.