Created
May 7, 2013 15:36
-
-
Save christophergregory/5533568 to your computer and use it in GitHub Desktop.
Center image within parent element
This file contains hidden or 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
(function($) { | |
$.fn.centerWithinParent = function() { | |
return this.each(function(){ | |
var $this = $(this), | |
parentPosition = $this.parent().css('position'); | |
if (parentPosition !== "absolute" || parentPosition !== "relative") { | |
$this.parent().css('position', 'relative'); | |
} | |
var w = $this.width(), | |
h = $this.height(), | |
parent_w = $this.parent().width(), | |
parent_h = $this.parent().height(), | |
margin_l = -w/2, | |
margin_t = -h/2; | |
// Adjust img size if either dimension is smaller than parent dimensions | |
if (w < parent_w) { | |
h = (h/w) * parent_w; | |
w = parent_w; | |
margin_l = -w/2; | |
margin_t = -h/2; | |
} | |
if (h < parent_h) { | |
w = (w/h) * parent_h; | |
h = parent_h; | |
margin_t = -h/2; | |
margin_l = -w/2; | |
} | |
// Adjust img size if image is way larger than parent div | |
if (w > parent_w || h > parent_h) { | |
adj_h = (h/w) * parent_w; | |
adj_w = parent_w; | |
if (adj_h < parent_h || adj_w < parent_w) { | |
adj_w = (w/h) * parent_h; | |
adj_h = parent_h; | |
if (adj_h >= parent_h || adj_w >= parent_w) { | |
h = adj_h; | |
w = adj_w; | |
margin_l = -w/2; | |
margin_t = -h/2; | |
} | |
} else { | |
h = adj_h; | |
w = adj_w; | |
margin_l = -w/2; | |
margin_t = -h/2; | |
} | |
} | |
$this.css({ | |
position: "absolute", | |
width: w + "px", | |
height: h + "px", | |
left: "50%", | |
top: "50%", | |
marginTop: margin_t + "px", | |
marginLeft: margin_l + "px" | |
}); | |
}); | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment