Skip to content

Instantly share code, notes, and snippets.

@bgkittrell
Created October 17, 2010 02:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgkittrell/630462 to your computer and use it in GitHub Desktop.
Save bgkittrell/630462 to your computer and use it in GitHub Desktop.
Center Horizontal and Vertically using Prototype
Element.addMethods({
centerHorizontally: function(element) {
if (!(element = $(element))) return;
var vpWidth = $(document).viewport.getWidth();
var width = element.getWidth();
element.style.left = (vpWidth / 2) - (width / 2) + 'px';
return element;
},
centerVertically: function(element) {
if (!(element = $(element))) return;
var vpHeight = $(document).viewport.getHeight();
var height = element.getLayout().get('margin-box-height');
var scrollTop = $(document).viewport.getScrollOffsets().top;
var avTop = (vpHeight / 2) - (height / 2) + scrollTop;
if (avTop <= 10)
avTop = 10;
element.style.top = avTop+ 'px';
return element;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment