Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto resize image to fit proportions but don't stretch

Tags:

html

css

I want to resize an image based on screen size but I don't want that image to exceed its actuall pixels when screen is too big. So far I managed to do this

<div align="center" style="position:static; height: 100%; width: 100%; top:0;left 0;">
<img src="myImg.png" style="width: 80%">
</div>

This maintains the proportions I want but when Screen is too big it also stretches the image. I don't want that.

like image 470
ThanosFisherman Avatar asked Jun 05 '15 15:06

ThanosFisherman


People also ask

How do you resize a picture without stretching it?

Choose Edit > Content-Aware Scale. Use the bottom transformation handle to click-and-drag it to the top. Then, click on the checkmark found on the Options panel to commit to the changes. Then, press Ctrl D (Windows) or Command D (macOS) to deselect, and now, you have a piece that perfectly fits within the space.

How do I fit a div image without stretching it?

Those images on the site you linked to are actual size, so the simple answer is just to resize the image. You can't really do this without "stretching" the image if the image happens to be less than 300px wide or tall, but you can do it without changing the ratio, which is what I think you mean.


2 Answers

The css for a responsive image is as follows:

    max-width: 100%;
    height: auto;

This will make the image scale down with the size of its container, without exceeding the image's natural width. However, using width: 100%; will force the image to be as wide as its container, regardless of the image's actual size.

A few other notes:

  • align="center" is deprecated. You should use css to align content, so text-align: center;.
  • Using position: static; is unnecessary, as it is the default value for the position property. The only time I can think of where you'd need to use this is if you need to override some other css.
  • Unless you are absolute positioning your div (which you are not), then top: 0; left: 0; will do nothing.

Without seeing the rest of your code, I think this would be the best solution for what you are trying to accomplish:

    <div style="text-align: center;">
       <img src="myImg.png" style="max-width: 100%; height: auto;" alt="FYI, image alt text is required" />
    </div>
like image 165
ns1234 Avatar answered Oct 09 '22 04:10

ns1234


If you also set a max-width attribute, it will limit how large the image can get. like so:

<div align="center" style="position:static; height: 100%; width: 100%; top:0;left 0;">
    <img src="myImg.png" style="width: 80%; max-width: 300px;">
</div>

You can make this max-width any size you want, as long as it doesn't exceed the actual width of the image. Also possible with height.

like image 2
Laura Vaca Avatar answered Oct 09 '22 05:10

Laura Vaca