Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS max-width not giving proportional resizing

Tags:

css

resize

I have a narrow view that I am inserting some HTML into. Every once in awhile there is an image that is too wide, so I have been wrapping the original HTML string, using this CSS to keep it under control:

<style type="text/css">p{max-width:100%;}img {max-width:100%;}</style>
<div style=\"word-wrap:break-word\">
.
. ...original HTML inside the div wrapper...
.
</div>

But it doesn't scale the width and height of the images proportionally, so the result is a very distorted image. Is there something else I can do, preferably with CSS or something equally as easy?

This is embedded inside a webview in an iOS application. I don't want write code to parse through the original HTML and look for images. I need a simple solution that takes advantage of the methods that are supported by the native UIView class.


UPDATE:

Using the example in the answer below from Kyle, I think the problem is occurring with images that have embedded width and height attributes:

Kyle's example:

<div style="word-wrap:break-word">
<img src="http://www.francodacosta.com/wp-content/uploads/resize_200_150.png">
</div>
<img src="http://www.francodacosta.com/wp-content/uploads/resize_200_150.png">

Modified, with width and height added to the first image link

<div style="word-wrap:break-word">
<img src="http://www.francodacosta.com/wp-content/uploads/resize_200_150.png" WIDTH="100%" HEIGHT="100%">
</div>
<img src="http://www.francodacosta.com/wp-content/uploads/resize_200_150.png">

Both using this CSS:

div {width:100px;}
p{max-width:100%;}
img{max-width:100%;}

It really isn't making any difference whether the container width attribute is set or not. I tried it both ways.

As a matter of fact, in this case (link) it looks like the image is first scaled up by the width and height attributes, followed by the width being scaled down by the CSS max-width. This leads a a very bizarre effect.

like image 558
Jim Avatar asked Oct 16 '11 07:10

Jim


2 Answers

To maintain the right proportions use:

img {
  max-width: 100%;
  height: auto;
}

The height: auto fixes the proportions.

like image 100
Richard Avatar answered Sep 22 '22 03:09

Richard


It's really easy, just add a width to the parent.

div
{
    width: 100px;
}

Demo here.

like image 28
Kyle Avatar answered Sep 22 '22 03:09

Kyle