Scale image to fit a bounding box

前端 未结 13 2112
轻奢々
轻奢々 2020-11-27 10:17

Is there a css-only solution to scale an image into a bounding box (keeping aspect-ratio)? This works if the image is bigger than the container:

img {
  max-         


        
13条回答
  •  孤街浪徒
    2020-11-27 10:43

    This example to stretch the image proportionally to fit the entire window. An improvisation to the above correct code is to add $( window ).resize(function(){});

    function stretchImg(){
        $('div').each(function() {
          ($(this).height() > $(this).find('img').height()) 
            ? $(this).find('img').removeClass('fillwidth').addClass('fillheight')
            : '';
          ($(this).width() > $(this).find('img').width()) 
            ? $(this).find('img').removeClass('fillheight').addClass('fillwidth')
            : '';
        });
    }
    stretchImg();
    
    $( window ).resize(function() {
        strechImg();
    });
    

    There are two if conditions. The first one keeps checking if the image height is less than the div and applies .fillheight class while the next checks for width and applies .fillwidth class. In both cases the other class is removed using .removeClass()

    Here is the CSS

    .fillwidth { 
       width: 100%;
       max-width: none;
       height: auto; 
    }
    .fillheight { 
       height: 100vh;
       max-width: none;
       width: auto; 
    }
    

    You can replace 100vh by 100% if you want to stretch the image with in a div. This example to stretch the image proportionally to fit the entire window.

提交回复
热议问题