Last active
December 29, 2015 17:39
-
-
Save beshur/7706062 to your computer and use it in GitHub Desktop.
jQuery blockPosition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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