Explain Codes LogoExplain Codes Logo

Scale image to fit a bounding box

html
responsive-design
object-fit
background-image
Alex KataevbyAlex Kataev·Aug 15, 2024
TLDR

Confining an image within a bounding box can be effortlessly achieved using CSS, specifically by applying max-width and max-height both set to 100%, along with object-fit: contain. Here’s a concise example:

<div style="width: 300px; height: 200px; overflow: hidden;"> <img src="image.jpg" style="max-width: 100%; max-height: 100%; object-fit: contain;" alt=""> </div>

This code snippet ensures image aspect ratio is maintained while the image is constrained within the specified bounding box dimensions.

Detailed exploration

Utilizing object-fit and object-position

Let's say you want your image to fill up the entire bounding box. This can be achieved using object-fit: cover, in conjunction with object-position to specify the image's position.

img { width: 100%; height: 100%; object-fit: cover; /* The image will cover the entire div */ object-position: center; /* The center of the image will be the center of the div */ }

And remember, if your image starts to believe it's a spacecraft and tries to escape its container, object-fit: scale-down can pull it right back in. This property downscales the image if necessary, but leaves smaller images at their original size.

Subtleties of scaling background images

Sometimes, you want to use an image as a background element rather than a content piece. The following example sets up the perfect stage for your image to perform on.

.bg-container { background-image: url('image.jpg'); background-size: contain; /* Our image respects boundaries */ background-repeat: no-repeat; /* No clones allowed */ background-position: center; /* Get in the spotlight */ width: 100%; height: 100%; }

The background-size: contain gives the image a visible boundary, while background-repeat: no-repeat stops rampant cloning. background-position: center grabs the image by its collar and shoves it into the spotlight, front and center.

Catering to browser compatibility

While object-fit is supported far and wide across browsers, Internet Explorer tends to live in its own world sometimes. In these instances, a fallback using transform can be handy. To understand if object-fit is supported on every user's browser, check out compatibility metrics here.

Miss flexibility — Responsive layouts

When you're dealing with a responsive layout, consider the aspect-ratio of your image-to-container. Use JavaScript to add classes based on the specified ratio. Transforms and translations are also useful tools, especially when you're designing for legacy browsers that do not support object-fit.

Interactive experimentation

There's nothing like rolling up your sleeves and diving in headfirst. Visit W3Schools to get your hands dirty and learn as you experiment.