How to set an image's width and height without stretching it?

If I have:

#logo {
    width: 400px;
    height: 200px;
}

then

<img id="logo" src="logo.jpg"/>

will stretch to fill that space. I want the image to stay the same size, but for it to take up that much space in the DOM. Do I have to add an encapsulating <div> or <span>? I hate adding markup for styling.


Yes you need an encapsulating div:

<div id="logo"><img src="logo.jpg"></div>

with something like:

#logo { height: 100px; width: 200px; overflow: hidden; }

Other solutions (padding, margin) are more tedious (in that you need to calculate the right value based on the image's dimensions) but also don't effectively allow the container to be smaller than the image.

Also, the above can be adapted much more easily for different layouts. For example, if you want the image at the bottom right:

#logo { position: relative; height: 100px; width: 200px; }
#logo img { position: absolute; right: 0; bottom: 0; }

2017 answer

CSS object fit works in all current browsers. It allows the img element to be larger without stretching the image.

You can add object-fit: cover; to your CSS.


Load the image as a background for a div.

Instead of:

<img id='logo' src='picture.jpg'>

do

<div id='logo' style='background:url(picture.jpg)'></div>

All browsers will crop the part of the image that doesn't fit.
This has several advantages over wrapping it an element whose overflow is hidden:

  1. No extra markup. The div simply replaces the img.
  2. Easily center or set the image to another offset. eg. url(pic) center top;
  3. Repeat the image when small enough. (Ok, I don't know, why you would want that)
  4. Set a bg color in the same statement, easily apply the same image to multiple elements, and everything that applies to bg images.

Update: This answer is from before object-fit; you should now probably use object-fit/object-position.

It is still useful for older browsers, for extra properties (such as background-repeat), and for edge cases (For example, workaround Chrome bugs with flexbox and object-position and FF's (former?) issues with grid + autoheight + object-fit. Wrapper divs in grid / flexbox often give... unintuitive results.)