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; }
CSS Image size, how to fill, but not stretch?
You can use the css property object-fit
. ("sets how the content of a replaced element, such as an <img>
or <video>
, should be resized to fit its container.")
.cover {
object-fit: cover;
width: 50px;
height: 100px;
}
<img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" />
How to resize the image without stretching and distorting it
You can use the object-fit property to display the image correctly regardless of the aspect ratio of the containing box or image. This way you can have uniform sized boxes with any image inside.
.pt-cv-wrapper img {
object-fit: cover;
}
Here is a polyfill for IE and Edge.
How to set all images to equal width and height without stretching
Are you sure this isn't what you want? The image will scale to the container fine, and the spare space is filled by the container's background. Also, the image is centred perfectly, no matter what the dimensions.
.img-container {
width: 40px;
height: 40px;
border: 1px solid;
position: relative;
}
.img-container img {
width: 100%;
height: auto;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="img-container">
<img src="http://lorempixel.com/400/200" alt="Random image">
</div>
Related Topics
Adding a Background Image to a <Div> Element
Input Type=Password, Don't Let Browser Remember the Password
Style Not Working for Innerhtml in Angular
Html5 Phone Number Validation with Pattern
How to Validate the Size and Type of Input=File in HTML5
How to Select an Element That Has a Certain Class
Html/Css: Make a Div "Invisible" to Clicks
CSS Selector with Period in Id
HTML Radio Buttons Allowing Multiple Selections
How to Write Fraction Value Using HTML
Margin:Auto;' Doesn't Work on Inline-Block Elements
Html:How to Show Images in a Textarea
How to Hide Table Row Overflow
How to Hide Drop Down Arrow in IE8 & IE9
Specifying Content of an Iframe Instead of the Src Attribute to a Page