html5 - Fill div with cropped image, preserve aspect ratio -
i have divs on page containing imgs. on image-click, opened in lightbox, inside div, should fill div completely, preserve aspect ratio.
this achieved far, problem aspect ratio not preserved when image in portrait-mode.
so need css-method center images vertically , horizontally while filling wrapping div (and of course cropping overflowing parts of image).
is possible, css only, or js required? browser-compatibility ie8 , higer , modern browsers.
solved js/jquery:
function resizeimages(){ $("#container img").each(function() { var thisheight = $(this).height(); var thiswidth = $(this).width(); var containerwidth = $(this).parent().width(); var containerheight = $(this).parent().height(); var diff = 0; if(thisheight > thiswidth){ //portrait $(this).css("width","100%"); thisheight = $(this).height(); diff = thisheight - containerheight; $(this).css("margin-top",-(diff/2)); } else if(thiswidth > thisheight){ //landscape $(this).css("height","100%"); var thiswidth = $(this).width(); if(thiswidth < containerwidth){ $(this).css("width", containerwidth); thiswidth = containerwidth; } diff = thiswidth - containerwidth; $(this).css("margin-left",-(diff/2)); } $(this).css("opacity",1); }); } the set-opacity 1 @ end because want show images when finished resizing, set them opacity:0 in css , after resizing show them.
this works me in container widths , image modes.
this require javascript implementation. jquery, can check if height larger width , vice versa.
you can this:
$(".container img").each(function(){ var thiswidth = $(this).width(); var thisheight = $(this).height(); if(thiswidth > thisheight) { $(this).css("width", "auto"); $(this).css("height", "100%"); } else if(thisheight > thiswidth) { $(this).css("width", "100%"); $(this).css("height", "auto"); } }); hope helps.
Comments
Post a Comment