user616
user616

Reputation: 855

Keep image aspect ratio when width exceeds height

I am trying to keep image aspect ration correct when either width > height OR height > width. I am having issue doing this when the width exceeds height, the image will overflow into the parent container. I dont want this to happen, instead readjust the image size to still keep the correct aspect ratio.

This example has an image of 640 x 480, with the ratio of 4:3

If i drag the container width smaller than the height i need even padding top/bottom without image overflow. If i drag the container wider than the height then i need even padding left/right without image overflow.

.main {
    height: 100%;
    width: 100%;
}
.wrapper {
    position: relative;
    padding-bottom: 75%;
}
.wrapper img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

<div class="main">
    <div class="wrapper">
        <img src="https://placeimg.com/640/480/animals" />
    </div>
</div>

JSFiddle

enter image description here

Upvotes: 0

Views: 328

Answers (2)

Sai Manoj
Sai Manoj

Reputation: 3849

You can set height:auto and width:100% to make your image responsive

.my-img {
  width: 100%;
  height: auto;
}
<img src="https://placeimg.com/640/480/animals" alt="Nature" class="my-img" >

Upvotes: 0

user11420945
user11420945

Reputation:

For modern browsers, you should only set the width. The browser will do everything else.

Example:

.main {
    height: auto;
    width: auto;
}
.wrapper {
    position: relative;
    padding-bottom: 75%;
}
.wrapper img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
}

Upvotes: 1

Related Questions