Вопрос

I am trying to horizontally center a dynamic element to dom level parents that have different widths.

I have most everything down but I am just calculating it wrong. Any help would be greatly appreciated.

NOTE: The width of the item I need centered is 20px

Script

$(function() {

$(".nav-menu").children("li").each(function() {

    $(this).on( "mouseenter", function(){   
    listWidth = $(this).find("a").width() /2 ; //<-- calculating width of each li
        $(this).find(".sub").prepend('<li id="nav-hover-state"></li>');
        $(this).find("#nav-hover-state").attr('style', 'margin-left:'+listWidth +'px');
    });

    $(this).on( "mouseleave", function(){   
        if($('.nav-container ul.nav-menu li .sub').attr('style','display:none')) {
        $(this).find("#nav-hover-state").remove();

    }
    });
}); 
Это было полезно?

Решение

Subtract half the size of your inner element

listWidth = ($(this).find("a").width() /2) - 10 ; //<-- calculating width of each li
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top