Search code examples
cssresponsive-designmedia-queriesaspect-ratio

Adjust height of image to 100% width without altering aspect ratio


I'm currently working on a project where we use a slider with images. This slider is displayed with width 100%, and currently we're adjusting the height to make the slider responsive, in case the user resizes the browser window or visits the website using their phone.

However, the website is for an artist who obviously does not want the image to be altered in any way, especially not altering with the aspect ratio. So what we're looking into is having height: auto to adjust the image height correctly according to the width: 100%, without altering the image (aspect ratio) itself.

This does not work like intended however, using the following code:

@media (min-width:1600px) {
    #header{
        height:auto;
        width: 100%;
        min-height: 630px;
        background-size: 100% auto;
    }

    #slidershadow {
        height: 630px;
    }
}

We need to have some min-height, otherwise we cannot display the slider controls correctly. Here is a picture of our current situation (first image) and the expected behaviour (second picture).

Adjust height of image to 100% width without altering aspect ratio

Is there a way to resize our slider responsive, but keeping the following in mind:

  • The aspect ratio of the image cannot be altered;
  • We cannot crop images too much (only slightly);
  • There is a minimum height to keep in mind;

If it helps, all images in the slider have the same size.


Solution

  • You have to give a max-width:100% to your img.

    Plus background-size only works when you are working with background-images.

    Since you are applying max-width to your img there is no need to apply max-width to its parent #header

    Last, but not least try not use min-height and height:auto at same time in the same selector.

    Below is a working snippet according to the above comments:

    img {
      max-width: 100%;
      height: auto
    }
    @media (min-width: 1280px) {
      #header {
        min-height: 500px;
      }
    }
    @media (min-width: 1600px) {
      #header {
        min-height: 630px;
      }
    }
    <div id="header">
      <img src="http://placehold.it/1920x630" />
    </div>