Skip to content

Instantly share code, notes, and snippets.

@sardbaba
Created December 11, 2015 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sardbaba/a4f2b86d937533781f0e to your computer and use it in GitHub Desktop.
Save sardbaba/a4f2b86d937533781f0e to your computer and use it in GitHub Desktop.
jQuery plugin for centering vertically and/or horizontally
(function( $ ) {
$.fn.vcenter = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px");
return this;
}
$.fn.hcenter = function () {
this.css("position","absolute");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft()) + "px");
return this;
}
}( jQuery ));
@sardbaba
Copy link
Author

Usage:

$('#myelement').vcenter();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment