Skip to content Skip to sidebar Skip to footer

How To Give Image A Max-height But Retain Aspect Ratio?

The image is 100% of the document width. I want the max-height of the image to be 2/3 of the screen height but to retain aspect ratio, and for the image to be centered. Here is a F

Solution 1:

for setting div width according to image width try this:

var image = newImage()
image.onload = function(){
  $('.image-wrapper').width = image.width
}
image.src = 'http://designyoutrust.com/wp-content/uploads/2013/06/376.jpg';

Solution 2:

image {
display: block;
max-width: 119.0525vh;
max-height: 67vh;
width: auto;
height: auto;
}

source: CSS force image resize and keep aspect ratio

Solution 3:

If you application is intent to use any king of image in terms of aspect ratio and resolution. Then you can use below concept:

HTML:

     <img src="@Model.ThumbnailUrl"id="imageThumbnail">

Javascript:

<script>
    $(document).ready(function () {
        $('#imageThumbnail').each(function () {

            var maxWidth = 601; // Max width for the imagevar maxHeight = 257.14;    // Max height for the imagevar ratio = 0;  // Used for aspect ratiovar width = $(this).width();    // Current image widthvar height = $(this).height();  // Current image height// If Height width are sameif (height === width) {
                $(this).css("height", maxHeight);
                $(this).css("width", maxHeight);
            }

            // Check if the current width is larger than the maxif (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 maxif (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
            }
        });
    });
</script>

Post a Comment for "How To Give Image A Max-height But Retain Aspect Ratio?"