How do I fit an image (img) inside a div and keep the aspect ratio?
Maintain your image’s aspect ratio and fit it perfectly inside a div by utilizing the object-fit: contain;
in your CSS. This method enables your image to fill the div completely without causing any distortions.
Use this class for your <img>
tag inside your div:
This approach ensures the image preserves its proportional dimensions within the container div.
Working with specific div dimensions
Setting fixed dimensions
Ensure your container div has fixed dimensions, this sets the stage to perfectly size your content. For example, with a div of 48x48 pixels, set:
Then apply the container
class to your div:
Fall back to JavaScript for legacy browsers
It's important to remember that the object-fit
property may not always work due to browser compatibility issues, especially with IE. In such cases, utilizing a JavaScript fallback can be a lifesaver:
Improve performance with JavaScript libraries
Consider using JS libraries like Lodash or Underscore for throttling or debouncing the adjustImage function for a significant performance boost.
Advanced applications in Responsive CSS
Aspect ratio for responsive design
In the world of modern CSS, the aspect-ratio
property provides greater control:
Apply this class to your container div and it will maintain a square aspect ratio even as the div's size alters.
Deliver backup image for unsupported formats
Providing a backup image is always a good idea in case a certain image format isn't supported:
Overflow for any overspill
Utilizing the overflow property in combination with flexbox
on the container div
allows for centering and managing any overspill, especially if the images are larger:
Utilize srcset for different resolutions
Use the srcset
attribute for images, which provides multiple sources based on the resolution to allow the browser to choose the best one:
Was this article helpful?