CSS force image resize and keep aspect ratio


Translate

I am working with images, and I ran across a problem with aspect ratios.

<img src="big_image.jpg" width="900" height="600" alt="" />

As you can see, height and width are already specified. I added CSS rule for images:

img {
  max-width:500px;
}

But for big_image.jpg, I receive width=500 and height=600. How I can set images to be re-sized, while keeping their aspect ratios.


All Answers
  • Translate

    img {
      display: block;
      max-width:230px;
      max-height:95px;
      width: auto;
      height: auto;
    }
    <p>This image is originally 400x400 pixels, but should get resized by the CSS:</p>
    <img width="400" height="400" src="http://i.stack.imgur.com/aEEkn.png">

  • Translate

    The solutions below will allow scaling up and scaling down of the image, depending on the parent box width.

    All images have a parent container with a fixed width for demonstration purposes only. In production, this will be the width of the parent box.

    Best Practice (2018):

    This solution tells the browser to render the image with max available width and adjust the height as a percentage of that width.

    .parent {
      width: 100px;
    }
    
    img {
      display: block;
      width: 100%;
      height: auto;
    }
    <p>This image is originally 400x400 pixels, but should get resized by the CSS:</p>
    <div class="parent">
      <img width="400" height="400" src="https://placehold.it/400x400">
    </div>

  • Translate

    I've struggled with this problem quite hard, and eventually arrived at this simple solution:

    object-fit: cover;
    width: 100%;
    height: 250px;
    

    You can adjust the width and height to fit your needs, and the object-fit property will do the cropping for you.

    Cheers.


  • Translate

    The background-size property is ie>=9 only, but if that is fine with you, you can use a div with background-image and set background-size: contain:

    div.image{
        background-image: url("your/url/here");
        background-size: contain;
        background-repeat: no-repeat;
        background-position: center;
    }
    

    Now you can just set your div size to whatever you want and not only will the image keep its aspect ratio it will also be centralized both vertically and horizontally within the div. Just don't forget to set the sizes on the css since divs don't have the width/height attribute on the tag itself.

    This approach is different than setecs answer, using this the image area will be constant and defined by you (leaving empty spaces either horizontally or vertically depending on the div size and image aspect ratio), while setecs answer will get you a box that exactly the size of the scaled image (without empty spaces).

    Edit: According to the MDN background-size documentation you can simulate the background-size property in IE8 using a proprietary filter declaration:

    Though Internet Explorer 8 doesn't support the background-size property, it is possible to emulate some of its functionality using the non-standard -ms-filter function:

    -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='path_relative_to_the_HTML_file', sizingMethod='scale')";
    

  • Translate

    Very similar to some answers here, but in my case I had images that sometimes were taller, sometimes larger.

    This style worked like a charm to make sure that all images use all available space, keep the ratio and not cuts:

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

  • Translate

    Remove the "height" property.

    <img src="big_image.jpg" width="900" alt=""/>
    

    By specifying both you are changing the aspect ratio of the image. Just setting one will resize but preserve the aspect ratio.

    Optionally, to restrict oversizings:

    <img src="big_image.jpg" width="900" alt="" style="max-width:500px; height:auto; max-height:600px;"/>
    

  • Translate

    Just add this to your css, It will automaticly shrink and expand with keeping the original ratio.

    img {
        display: block;
        max-width: 100%;
        max-height: 100%;
        width: auto;
        height: auto;
    }
    

  • Translate

    There is no standard way to preserve aspect ratio for images with width, height and max-width specified together.

    So we are forced either to specify width and height to prevent page “jumps” during loading images, or to use max-width and not specify dimensions for images.

    Specifying just width (without height) typically makes not much sense, but you can try to override the height HTML-attribute by adding a rule like IMG {height: auto; } into your stylesheet.

    See also the related Firefox bug 392261.


  • Translate

    Set the CSS class of your image container tag to image-class:

    <div class="image-full"></div>
    

    and add this you your CSS stylesheet.

    .image-full {
        background: url(...some image...) no-repeat;
        background-size: cover;
        background-position: center center;
    }
    

  • Translate

    To maintain a responsive image while still enforcing the image to have a certain aspect ratio you can do the following:

    HTML:

    <div class="ratio2-1">
       <img src="../image.png" alt="image">
    </div>
    

    And SCSS:

    .ratio2-1 {
      overflow: hidden;
      position: relative;
    
      &:before {
        content: '';
        display: block;
        padding-top: 50%; // ratio 2:1
      }
    
      img {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
      }
    }
    

    This can be used to enforce a certain aspect ratio, regardless of the size of the image that authors upload.

    Thanks to @Kseso at http://codepen.io/Kseso/pen/bfdhg. Check this URL for more ratios and a working example.


  • Translate

    https://jsfiddle.net/sot2qgj6/3/

    Here is the answer if you want to put image with fixed percentage of width, but not fixed pixel of width.

    And this will be useful when dealing with different size of screen.

    The tricks are

    1. Using padding-top to set the height from width.
    2. Using position: absolute to put image in the padding space.
    3. Using max-height and max-width to make sure the image will not over the parent element.
    4. using display:block and margin: auto to center the image.

    I've also comment most of the tricks inside the fiddle.


    I also find some other ways to make this happen. There will be no real image in html, so I personly perfer the top answer when I need "img" element in html.

    simple css by using background http://jsfiddle.net/4660s79h/2/

    background-image with word on top http://jsfiddle.net/4660s79h/1/

    the concept to use position absolute is from here http://www.w3schools.com/howto/howto_css_aspect_ratio.asp


  • Translate

    To force image that fit in a exact size, you don't need to write too many codes. It's so simple

    img{
        width: 200px;
        height: auto;
        object-fit: contain; /* Fit logo in the image size */
            -o-object-fit: contain; /* Fit logo fro opera browser */
        object-position: top; /* Set logo position */
            -o-object-position: top; /* Logo position for opera browser */
        }
    <img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png" alt="Logo">

  • Translate

    You can create a div like this:

    <div class="image" style="background-image:url('/to/your/image')"></div>
    

    And use this css to style it:

    height: 100%;
    width: 100%;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: contain; // this can also be cover
    

  • Translate

    You can use this:

    img { 
        width: 500px; 
        height: 600px; 
        object-fit: contain; 
        position: relative; 
        top: 50%; 
        transform: translateY(-50%); 
    }
    

  • Translate

    This will make image shrink if it's too big for specified area (as downside, it will not enlarge image).

    The solution by setec is fine for "Shrink to Fit" in auto mode. But, to optimally EXPAND to fit in 'auto' mode, you need to first put the received image into a temp id, Check if it can be expanded in height or in width (depending upon its aspect ration v/s the aspect ratio of your display block),

    $(".temp_image").attr("src","str.jpg" ).load(function() { 
        // callback to get actual size of received image 
    
        // define to expand image in Height 
        if(($(".temp_image").height() / $(".temp_image").width()) > display_aspect_ratio ) {
            $(".image").css('height', max_height_of_box);
            $(".image").css('width',' auto');
        } else { 
            // define to expand image in Width
            $(".image").css('width' ,max_width_of_box);
            $(".image").css('height','auto');
        }
        //Finally put the image to Completely Fill the display area while maintaining aspect ratio.
        $(".image").attr("src","str.jpg");
    });
    

    This approach is useful when received images are smaller than display box. You must save them on your server in Original Small size rather than their expanded version to fill your Bigger display Box to save on size and bandwidth.


  • Translate

    img {
      max-width: 80px; /* Also works with percentage value like 100% */
      height: auto;
    }
    <p>This image is originally 400x400 pixels, but should get resized by the CSS:</p>
    <img width="400" height="400" src="https://i.stack.imgur.com/aEEkn.png">
    
    <p>Let's say the author of the HTML deliberately wants
      the height to be half the value of the width,
      this CSS will ignore the HTML author's wishes, which may or may not be what you want:
    </p>
    <img width="400" height="200" src="https://i.stack.imgur.com/aEEkn.png">

  • Translate

    How about using a pseudo element for vertical alignment? This less code is for a carousel but i guess it works on every fixed size container. It will keep the aspect ratio and insert @gray-dark bars on top/bottom or left/write for the shortest dimension. In the meanwhile the image is centered horizontally by the text-align and vertically by the pseudo element.

        > li {
          float: left;
          overflow: hidden;
          background-color: @gray-dark;
          text-align: center;
    
          > a img,
          > img {
            display: inline-block;
            max-height: 100%;
            max-width: 100%;
            width: auto;
            height: auto;
            margin: auto;
            text-align: center;
          }
    
          // Add pseudo element for vertical alignment of inline (img)
          &:before {
            content: "";
            height: 100%;
            display: inline-block;
            vertical-align: middle;
          }
        }
    

  • Translate

    Fullscreen presentation:

    img[data-attribute] {height: 100vh;}
    

    Keep in mind that if the view-port height is greater than the image the image will naturally degrade relative to the difference.