Simeon Mark Fernandes
Simeon Mark Fernandes

Reputation: 107

Maintaining image aspect ratio for a fixed height

I have an image of height 600px. And I'm using it with an img tag, than a background image. Reason is because of responsiveness. I want the image to resize based on screen sizes. But i want my image to be of height 300px. Now if i set the max-height:300px and width:100%. The image looks stretched. Is there a way for the image to be proportioned as well as responsive based on screen sizes?

This is for a bootstrap carousel image.

Upvotes: 1

Views: 4290

Answers (1)

Sebastian Brosch
Sebastian Brosch

Reputation: 43564

Set width:auto;, like the following example:

img.non-stretched {
  max-height:300px;
  width:auto;
}
img.stretched {
  max-height:300px;
  width:100%;
}
<img class="non-stretched" src="http://placehold.it/600x600"/>
<img class="stretched" src="http://placehold.it/600x600"/>

The initial value of width is auto so you can remove the width property. But it's safer to set the width in your case because a used framework or other stylesheet can overwrite the rules with another value.

You can find more information about the width property here: https://www.w3.org/TR/CSS2/visudet.html#the-width-property

Upvotes: 3

Related Questions