Skip to content

Instantly share code, notes, and snippets.

@beshur
Last active December 29, 2015 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beshur/7706062 to your computer and use it in GitHub Desktop.
Save beshur/7706062 to your computer and use it in GitHub Desktop.
jQuery blockPosition
// jQuery function to center the image and stretch it to completely fill
// the parent, stretchin either height or width, when needed
//
// originally written by Ivan Ryzhenko
// https://gist.github.com/beshur/7706062
//
// Usage:
// blockPosition($(img_you_need_to_center), $(optional_relative));
function blockPosition(obj, relative){
obj.each(function(index, element) {
$(this).css({'width': '', 'height': ''});
// var w = $(this).width();
// var h = $(this).height();
var w = $(this).outerWidth();
var h = $(this).outerHeight();
// console.log(w,h);
var d = w/h;
if(relative) {
var parent = relative;
} else {
var parent = $(this).parent();
}
var w_p = parent.width();
var h_p = parent.height();
var d_p = w_p/h_p;
if(d > d_p) {
h = h_p;
w = h*d;
m = "0 0 0 " + (-w/2) + "px";
l = "50%";
t = 0;
} else {
w = w_p;
h = w/d;
m = -h/2 + "px 0 0 0";
t = "50%";
l = 0;
}
$(this).css({"width": w + "px", "height" : h + "px", "margin": m, "top": t, "left": l, "position": "relative"}).addClass("is_blockpos");
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment