Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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.

like image 861
Paul Tarjan Avatar asked Nov 14 '09 02:11

Paul Tarjan


People also ask

How do I make an image fit without stretching CSS?

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.") Related: object-position (specifies the alignment of an element's contents within its box.)

How do you make a picture the same width and height?

container { width: 50%; } . container img { width: 100%; height: 400px; //this should be the same as the width value.. }

How do you maintain height width ratio of an image?

The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.


2 Answers

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; } 
like image 65
cletus Avatar answered Nov 02 '22 18:11

cletus


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.

like image 21
Dante Avatar answered Nov 02 '22 18:11

Dante