Center Aligning a Child Menu Drop Down with JQuery

17th June, 2012 in Technical

center align menuIt's tricky center aligning a drop down menu using CSS only, so we use a simple JQuery method to calculate the parent width and work out the child menu widths, and set them accordingly.

If a user does not have Javascript enabled, then the menu still works, but is left aligned to the parent menu instead.

$("#header-menu ul li").each( function()
{
    if( $(this).find("ul").length > 0 )
    {
        var parent_width = $(this).outerWidth( true );
        var child_width = $(this).find("ul").outerWidth( true );
        var new_width = parseInt((child_width - parent_width)/2);
        $(this).find("ul").css('margin-left', -new_width+"px");
    }
});

Leave a Reply

Recent