2

Is there any way that I can use just HMTL and CSS to force an image to resize to fit a fixed dimension while maintaining its aspect ratio (without stretching/shrinking)?

Consider my required dimension to be a 64x64 pixel square, and the following cases for images I want to fit within this dimension:

  1. A 64x64 pixel image
  2. An image 96 pixels wide and 135 pixels high
  3. An image 135 pixels high and 96 pixels wide

I've been able to figure out a way to solve either 1 & 2 or 1 & 3 by explicitly declaring the image's height="64px" and width="64px" respectively, but one does not work for both, and declaring both causes the image to stretch or shrink.

Is there a way to solve this problem only using HTML and CSS?

1 Answer 1

3

use max-width and max-height instead. don't set width/height in css.

style="max-width: 64px; max-height: 64px;"
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, I honestly thought I had tried that. Thank you for the quick and obviously solution.
@Wex: max-width does not work in IE8, images will show max-width size but they will go on occupying their real width, you can try with an horizontal shape rectangle image and set max-height:60px; max-width:80px; Issue explained also here reference.sitepoint.com/css/max-width#

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.