Wex
Wex

Reputation: 15695

HTML/CSS - Possible way to scale image to fit a certain dimension while maintaining the its aspect ratio?

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?

Upvotes: 2

Views: 948

Answers (1)

galchen
galchen

Reputation: 5290

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

style="max-width: 64px; max-height: 64px;"

Upvotes: 3

Related Questions