Search code examples
htmlcssresponsive-designresponsive-images

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?


Solution

  • 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;
    }