Simple element centering with jQuery


/ Published in: JavaScript
Save to your folder(s)

I like how this site uses jQuery to center some elements and I wanted to save the code incase they change their site ever.


Copy this code and paste it in your HTML
  1. jQuery.fn.centerx = function () {
  2. this.css("position","absolute");
  3. this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
  4. return this;
  5. }
  6.  
  7. jQuery.fn.center = function () {
  8. this.css("position","absolute");
  9. this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
  10. this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
  11. return this;
  12. }
  13.  
  14. $(function(){
  15. $("#header").centerx();
  16. $("#dropzone, #browser").center();
  17. });
  18. $(window).resize(function(){
  19. $("#header").centerx();
  20. $("#dropzone, #browser").center();
  21. });

URL: http://general-metrics.com/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.