Bin Chen Bin Chen - 2 years ago 138
HTML Question

How do I fit an image (img) inside a div and keep the aspect ratio?

I have a 48x48 div and inside it there is an img element, I want to fit it into the div without losing any part, in the mean time the ratio is kept, is it achievable using html and css?

Answer Source

You will need some JavaScript to prevent cropping if you don't know the dimension of the image at the time you're writing the css.

HTML & JavaScript

<div id="container">
    <img src="something.jpg" alt="" />

<script type="text/javascript">
(function() {

var img = document.getElementById('container').firstChild;
img.onload = function() {
    if(img.height > img.width) {
        img.height = '100%';
        img.width = 'auto';



#container {
   width: 48px;
   height: 48px;

#container img {
   width: 100%;

If you use a JavaScript Library you might want to take advantage of it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download