jQuery: center the viewport on an element

If you have a page that's very long vertically (something that requires a scrollbar) and you want to center the viewport on a specific element do this:

var elem_top = $("#my_item").offset()['top'];
var viewport_height = $(window).height();

// Scroll to the middle of the viewport
var my_scroll = elem_top - (viewport_height / 2);
Leave A Reply
All content licensed under the Creative Commons License