Skip to content

Instantly share code, notes, and snippets.

@adamculpepper
Last active August 29, 2015 14:13
Show Gist options
  • Save adamculpepper/21134103ca5badb9b1ef to your computer and use it in GitHub Desktop.
Save adamculpepper/21134103ca5badb9b1ef to your computer and use it in GitHub Desktop.
Vertically Centering Elements with offset (jQuery)
/*
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