Explain Codes LogoExplain Codes Logo

Resize image proportionally with CSS?

html
responsive-design
css
image-resizing
Alex KataevbyAlex Kataev·Sep 12, 2024
TLDR

Effortlessly maintain an image's aspect ratio with CSS by setting the width to 100% and the height to auto along with object-fit: contain;. This combo resizes the image to fit its container without distortion:

img { width: 100%; /* Flexibility is key, just like in yoga */ height: auto; /* Let it go (automatically) */ object-fit: contain; /* Prevent the awkward stretches */ }

This keeps your images looking responsive and well-proportioned on various screen sizes.

Hail to scalable classes and setting limits

For customizable scaling, you can create a CSS class like .img.resize. It respects the natural aspect ratio of your images:

.img.resize { max-width: 100%; /* Go big or go home, but not too big */ max-height: 500px; /* More than enough for a classy portrait */ height: auto; /* Keep it real, keep it auto */ }

Implementing max-width and max-height provides boundaries for your images to stretch and shrink inside, preventing layout overflow and ensuring optimal display on a variety of devices.

The greatness of background scaling

If background images are your game, background-size: contain; is your play. This property scales the background image to fit within the content area, preserving its aspect ratio and ensuring it's entirely visible:

div.background { background-image: url('image.jpg'); background-size: contain; /* Like fitting a tiger in a box */ background-repeat: no-repeat; /* No twins wanted */ }

Shapeshift with transform

Sometimes, you might want to dynamically scale an image to half its size. Let's get creative with the transform property:

img.half-scale { transform: scale(0.5); /* I see you're a half-empty type of person */ -webkit-transform: scale(0.5); /* for the hipsters */ -ms-transform: scale(0.5); /* for nana and her IE9 */ }

Make it classy! Use class-based scaling for cleaner HTML and reuse opportunities.

object-fit to the rescue

The object-fit property lets you decide how content should resize within its container. Using object-fit: contain; with defined width and height, you can ensure full visibility without unnecessary stretches:

div.my-image { width: 100%; /* The limit is not the sky, but 100% */ height: 500px; /* Let's keep it within human height */ object-fit: contain; /* Fits like your favorite pair of jeans */ }

Mindful of responsive design

Always consider the responsive behavior of your images. Adjust image sizes for different screen resolutions and devices. Your users and their variety of screens will thank you.