Last active
August 29, 2015 14:13
-
-
Save adamculpepper/21134103ca5badb9b1ef to your computer and use it in GitHub Desktop.
Vertically Centering Elements with offset (jQuery)
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
/* | |
usage: | |
call function: centerThings(); | |
add class: "center-vert" | |
add offset (optional): data-center-offset="-3" | |
example: <div class="center-vert" data-center-offset="-3">text</div> | |
demo: http://jsfiddle.net/adamculpepper/kns0osky | |
*/ | |
function centerThings() { | |
$(".center-vert").each(function () { | |
var el = $(this); | |
var targetHeight = el.outerHeight(); | |
var parentHeight = el.parent().outerHeight(); | |
var targetCenter = (parentHeight / 2) - (targetHeight / 2); | |
var targetOffset = (el.attr("data-center-offset")) ? el.attr("data-center-offset") : 0; | |
var targetTotal = (targetCenter + parseInt(targetOffset)); | |
el.css({ | |
'position': 'relative', | |
'top': targetTotal | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment