Scale a div to fit in window but preserve aspect ratio

前端 未结 4 1124
梦毁少年i
梦毁少年i 2020-11-28 23:31

How can I scale a div to fit inside the browser view port but preserve the aspect ratio of the div. How can I do this using CSS and/or JQuery?

Thanks!

4条回答
  •  天涯浪人
    2020-11-29 00:18

    Thanks to Geoff for the tip on how to structure the math and logic. Here's my jQuery implementation, which I'm using to size a lightbox so it fills the window:

    var height = originalHeight;
    var width = originalWidth;
    aspect = width / height;
    
    if($(window).height() < $(window).width()) {
        var resizedHeight = $(window).height();
        var resizedWidth = resizedHeight * aspect;
    }
    
    else { // screen width is smaller than height (mobile, etc)
        var resizedWidth = $(window).width();
        var resizedHeight = resizedWidth / aspect;      
    }
    

    This is working well for me right now across laptop and mobile screen sizes.

提交回复
热议问题