Adam Griffiths
Adam Griffiths

Reputation: 782

Make image responsive maintaining aspect ratio, with padding either side

Here is a link to the working pen: https://codepen.io/Adam0410/pen/OBqRRN

HTML

<div id="imgWrapper">
  <img src="https://thestoryengine.co/wp-content/uploads/2017/11/The-crossroads-Section-images-02.png">
</div>

CSS

#imgWrapper {
  display: flex;
  justify-content: center;

  width: 100%;

  padding: 0 20px;
}

#imgWrapper img {
  width: 100%;
  max-width: 1660px;
  height: auto;
}

I don't want the image to exceed its original width (hence max-width) but I want it to scale down to the width of the viewport while maintaining its aspect ratio. Currently, the height does not scale with the width, why is this?

Upvotes: 2

Views: 633

Answers (2)

Matt
Matt

Reputation: 492

What about using the vm unit to your #imgWrapper making it always responsive:

#imgWrapper {
 display: flex;
 justyfy-content: center;
 vm: 100%;
 padding: 0 20px;
}

Upvotes: 0

Mārcis P
Mārcis P

Reputation: 326

Why do you need display flex to imgWrapper? Change it to block and it will work as expected. In case you need flex in there add it to other wrapper.

#imgWrapper {
  display: block;
}

Upvotes: 2

Related Questions