Skip to content

Instantly share code, notes, and snippets.

@kylejson
Last active August 29, 2015 14:15
Show Gist options
  • Save kylejson/d945f5fcaba38e4705a5 to your computer and use it in GitHub Desktop.
Save kylejson/d945f5fcaba38e4705a5 to your computer and use it in GitHub Desktop.
Center something with Jquery absolutely within the viewport
$.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft()) + "px");
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment