Vertical centering variable height image while maintaining max-width/height

后端 未结 3 1547
无人及你
无人及你 2020-11-30 08:37

I want to center an image of unknown width/height on a page, while making sure that it shrinks if it is bigger than the page (i.e. use max-width/max-heigh

3条回答
  •  星月不相逢
    2020-11-30 08:58

    Try something like this...

    Demo: http://jsfiddle.net/wdm954/jYnk8/1/

    $(function() {
    
        h = $('.img').height();
        w = $(window).height();
    
        if (h < w) { 
            $('.img').css('margin-top', (w - h) /2 + "px");
        }
        else {
            $('.img').height(w);
        }
    
    });
    

    (You can test different sizes by changing some CSS I have commented out.)

提交回复
热议问题