Here’s a little function I wrote that will auto-center any element with a class of “js-center”. It’s useful for centering anchor tags, or span tags (elements that are inline with the content) when their content is dynamic. Use this as a last resort! It’s better to do this with CSS if you can.


$('.js-center').each(function() {
var containerWidth = $(this).parent().width(); // not including padding
var elementWidth = $(this).outerWidth(); // including padding
var marginLeftValue = containerWidth / 2 – elementWidth / 2;

$(this).css('margin-left', marginLeftValue);
});

See the Pen Auto-center elements with jQuery by William (@bigwilliam) on CodePen.
0

 

Leave a Reply

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