Sophie S
Sophie S

Reputation: 31

Responsive cut and resize image

I'm trying to achieve something like this http://jsfiddle.net/Zex4S/1/ so when you resize the window, it image keeps its aspect ratio, but at the same time, I don't want the height of this image to change, it must remain constant, and zoom in if necessary.

I think it involves cropping the top and left margin, but I can't get it working

Something like this $this.css('margin-left', ($window.width() - this.width) / 2);

Any help would be greatly appreciated!

Upvotes: 0

Views: 508

Answers (2)

chrisgonzalez
chrisgonzalez

Reputation: 4213

You can do this 100% CSS if you don't mind swapping your img tag for a div with a background image. Just add the image url as an inline-style and bammo, success!

If you needed the img in the dom, you could always keep it within the .image container, size it to full size of the container, but make it transparent. Just a thought.

jsfiddle: http://jsfiddle.net/JTV66/

HTML:

<div class="image" style="background-image: url(http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg)"></div>

CSS:

body, html{
    width:100%;
    height:100%;
}

.image{
    width:100%;
    height:100%;
    background-size:contain;
    background-position:center center;
    background-repeat:no-repeat;
}

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

I assume you mean that you want the image to maintain it’s natural width & height but stay "centered" within it’s container if the window width is less than the image width.

You can do that using something like this:

var $img = $('img'),
    iw, ww;

$img.load(function() {
    iw = this.width; // save the natural width
});

$img.prop('complete') && $img.trigger('load'); // make sure load() is triggered

$(window).resize(function () {
    ww = $(this).width();
    if ( iw > ww ) { // if window width is less than image width, adjust margins
        $img.css('marginLeft', (iw-ww)/-2);
    }
}).trigger('resize');

Upvotes: 1

Related Questions