Posted By

rickygri on 09/05/12


Tagged

element jquery center


Versions (?)

jQuery center


 / Published in: JavaScript
 

Extend jQuery with a 'center' function. Use position:fixed to align center in viewport, or position:absolute inside a relatively positioned parent to center inside that parent.

  1. // Extend jQuery
  2. jQuery.fn.center = function () {
  3. this.css("position","fixed");
  4. this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop()) + "px");
  5. this.css("left", Math.max(0, (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft()) + "px");
  6. return this;
  7. }
  8.  
  9. // Center a div
  10. $(element).center();

Report this snippet  

You need to login to post a comment.