How to set an image's width and height without stretching it?
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:
- No extra markup. The div simply replaces the img.
- Easily center or set the image to another offset. eg.
url(pic) center top;
- Repeat the image when small enough. (Ok, I don't know, why you would want that)
- 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.)