user554114
user554114

Reputation: 11

Resizable / fluid images wrapped in a div?

im trying to get some images to resize automatically when a window resizes.

I have this working with the code below, however I would like to have a little more control over the image such as being able to set a min-height, any ideas??

also maybe wrap the images in a div so there is a little more control? Im not to good with js so any help or explanations would help

$(function() {
    var $img = $(".l");  
    var ratio;
    var offsetX = $img.offset().left;
    var offsetY = $img.offset().top;

    $(window).load(function () {
        ratio = $img.width() / $img.height();
        $(this).resize();
    });

    $(window).resize(function () {
        var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
        var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
        var availWidth = viewportWidth - offsetX - 70;
        var availHeight = viewportHeight - offsetY - 70;

        if (availWidth / availHeight > ratio) {
            $img.height(availHeight);
            $img.width(availHeight * ratio);
        } 
        else {
            $img.width(availWidth);
            $img.height(availWidth / ratio);
        }
    });
});

Upvotes: 0

Views: 354

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

Just use CSS:

img { width: 100%; }

You can then apply height or min-height as you need.

To see it working, resize the window of this fiddle:

Example fiddle

Upvotes: 1

Related Questions