Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/IE: stretch image to fit, preserve aspect ratio

In an HTML window, I am setting a custom body

<img src="file://[filename]">

to display an image.

Now I want to strectch the image to fit the available window, but preserve aspect ratio.

<img src="file://[filename]" width="100%" height="100">

stretches but also distorts the image.

Is there some HTML trickery to do that? IE only solution is fine, since this is in a hosted broweser control.

like image 841
peterchen Avatar asked Mar 13 '09 16:03

peterchen


People also ask

How do I resize an image and keep the aspect ratio in HTML?

You can preserve the aspect ratio by specifying only width and setting height to auto using CSS property. This will render a 400px wide image. The height is adjusted accordingly to preserve the aspect ratio of the original image.

How do I lock aspect ratio in HTML?

In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.

How do I preserve an image aspect ratio?

By 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. The end result is an image that scales up or down perfectly.

How do you autofit an image in HTML?

The max-height property sets the maximum height of an element, and the max-width property sets the maximum width of an element. To resize an image proportionally, set either the height or width to "100%", but not both. If you set both to "100%", the image will be stretched.


2 Answers

If you want to preserve aspect ratio, you only need to specify one dimension ie:

<img src="file://[filename]" width="100%" alt="" />

You can use javascript to determine max dimension and resize accordingly

<script type="text/javascript">
function getImgSize(id){
var pic = document.getElementById(id);
var h = pic.offsetHeight;
var w = pic.offsetWidth;
alert ('The image size is '+w+'*'+h);
}
</script>
like image 196
Philippe Avatar answered Oct 05 '22 10:10

Philippe


If you know either the height or width, you can set only that. The other dimension will be automatically set based on the aspect ratio of the image.

like image 25
tgecho Avatar answered Oct 05 '22 08:10

tgecho