Skip to content

Instantly share code, notes, and snippets.

@cobbman
Last active December 16, 2015 01:59
Show Gist options
  • Save cobbman/5358784 to your computer and use it in GitHub Desktop.
Save cobbman/5358784 to your computer and use it in GitHub Desktop.
jQuery: auto-center an element (button) within it's parent div
// Auto center buttons with class of js-center
// example of button HTML this would work for: <div id="sidebar-widget-stuff"><a class="btn js-center">Click Me</a></div>
(function(){
$('.js-center').each(function(){
var elementWidth = $(this).outerWidth(); // measures width including padding
var containerWidth = $(this).parent().width(); // measures width not including padding
var marginLeftValue = containerWidth/2 - elementWidth/2;
$(this).css('margin-left', marginLeftValue);
});
// grab width of each .js-center element
// grab width of container box
// set margin-left to 1/2 container box width - 1/2 element width
})();
@cobbman
Copy link
Author

cobbman commented Jun 17, 2013

Note that the above measurements consider the padding on the element. If that element's box-sizing methods change (i.e. in CSS box-sizing: content-box;) it could change which width is used here. Hope that made sense, if not just leave a comment and I'll get back to you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment