Skip to content

Instantly share code, notes, and snippets.

@adamculpepper
Last active August 29, 2015 14:04
Show Gist options
  • Save adamculpepper/c9ed91be1091eb420814 to your computer and use it in GitHub Desktop.
Save adamculpepper/c9ed91be1091eb420814 to your computer and use it in GitHub Desktop.
Center Element Based On Another Element
// general usage function call: centerElement(selector, target);
// add in: Parent is absolute
// add in: Parent is relative
$("li.dropdown").click(function(event) {
centerElement( $("ul.dropdown-menu"), $(event.target) );
});
function centerElement(selector, target) {
var selector = target.next(selector);
var selectorWidth = selector.outerWidth();
var targetWidth = target.outerWidth();
var selectorCenter = Math.abs(selectorWidth / 2) - (targetWidth / 2);
selector.css({ "margin-left": -1 * selectorCenter });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment