skip to Main Content

My mobile site shows a scrolling column of images which are at 100% width. However, some images can be taller than the viewport, which is undesirable. For those images, I want to cap the image height at 100vh and make the width as wide as possible (but necessarily less than 100% when the image is too tall for the viewport), preserving the aspect ratio.

How can I accomplish this with CSS?

2

Answers


  1. Chosen as BEST ANSWER

    I found this solution to force 100% width if possible, but also limit to the viewport height:

    img {
      max-height: 100vh;
      object-fit: contain;
      width: 100%;
    }
    

  2. If you wish to preserve the aspect ratio, a max-height property of 100vh should work in conjuction with max-width: 100%

    https://jsfiddle.net/pqn4yx6z/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search