1

I have to show photo images of users in a div of 120px by 120px. The problem is that images may have different sizes:

  • Be smaller
  • Greater
  • Do not be square. The big problem.

Is there any way to insert images inside the square without losing the aspect ratio?

Note: Images are displayed as background-image. I prefer CSS, but it could be javascript or jquery.

Very important: need to be supported by IE8.

Stickers
  • 75,527
  • 23
  • 147
  • 186
jpussacq
  • 573
  • 9
  • 29
  • 1
    You might consider using the [**background-size-polyfill**](https://github.com/louisremi/background-size-polyfill) for IE8 – Aziz Apr 19 '16 at 04:00

2 Answers2

-2

try to use jQuery. You can define required height and width of the picture while preserving the aspect ratio.

Check this example.

$(document).ready(function() {
$('.story-small img').each(function() {
    var maxWidth = 100; // Max width for the image
    var maxHeight = 100;    // Max height for the image
    var ratio = 0;  // Used for aspect ratio
    var width = $(this).width();    // Current image width
    var height = $(this).height();  // Current image height

    // Check if the current width is larger than the max
    if(width > maxWidth){
        ratio = maxWidth / width;   // get ratio for scaling image
        $(this).css("width", maxWidth); // Set new width
        $(this).css("height", height * ratio);  // Scale height based on ratio
        height = height * ratio;    // Reset height to match scaled image
        width = width * ratio;    // Reset width to match scaled image
    }

    // Check if current height is larger than max
    if(height > maxHeight){
        ratio = maxHeight / height; // get ratio for scaling image
        $(this).css("height", maxHeight);   // Set new height
        $(this).css("width", width * ratio);    // Scale width based on ratio
        width = width * ratio;    // Reset width to match scaled image
    }

});

Source: http://ericjuden.com/2009/07/jquery-image-resize/

vviston
  • 183
  • 1
  • 12
-3

Yes. You can maintain the aspect ratio of background images using the CSS rules:

background-size: cover;
background-size: contain;

More info: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

Michael Oakley
  • 383
  • 3
  • 5