I design & develop websites.

I am a designer & developer. I am a communicator & strategist. I can add value to your business.

jQuery vertical centre

I'm working on a super secret project for Hydrant at the moment which requires vertically centering an element on page load and keeping it centered on window re-size. Here's how it's done.

$(function() {
  $.fn.verticalCenter = function() {
    $(this).each(function() {
      $pageCenter = $(this).height() / 2;
      $windowCenter = $(window).height() / 2;
      $top = $windowCenter - $pageCenter;
      $(this).css({
        'position': 'absolute',
        'top' : $top + 'px'
      });
    });
  }
  myResize = function() {
   $('.page:visible').verticalCenter();
  }
  $(window).resize(myResize);
  myResize();
});

One Response to jQuery vertical centre

  1. chan says:

    this is a great script! i have a div footer 143px how can i set a margin on the script?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>