cjds cjds - 1 year ago 40
jQuery Question

How to resize image to fit DIV jQuery

I have square DIV and large portrait and landscape images.

I need to fit the image in a DIV with the extra part going


For eg. If portrait set width=width of div height:auto

Opposite for Lanscape.

I tried this script but it didn;t work

$(this).css('height', '300px');
$(this).css('width', 'auto');
$(this).css('width', '300px');
$(this).css('height', 'auto');


PS Images can't stretch and must scale


Use some CSS like this

.magic.portrait {
    height: 300px;
    width: auto;

.magic.landscape {
    width: 300px;
    height: auto;

and just add a class with your JS

    if($(this).width() > $(this).height()){

This also helps keep your application logic and styles nicely separated. Even better, add these classes server side, and avoid the JavaScript altogether.