How can I make a navigation menu fit its container? [horizontally]

ぃ、小莉子 提交于 2019-12-06 20:49:29
Nilpo

You'll need to do one of two things. Making all of your menu items a constant size is the easiest way to fill the container since your have hard-coded its size.

Your other option is to create some javascript that determines the difference between the width of the UL and the width of the parent div and then evenly distributes that space among the child elements by increasing the padding. The reason is that the LI will fit to its contents. You'll need to grow the contents to stretch the whole menu. You can see how I do that here. http://jsfiddle.net/Nilpo/GGQ4V/3/

$(window).load(function() {

var container = $('div.menu-main-menu-container');
var menu = $('ul.menu');

var difference = container.width() - menu.width();

if (difference > 0) {
    var count = menu.children().length;

    var pad = (difference / count) / 2;

    var total = 0;
    menu.children().each(function(){
        var el = $(this);
        var lpad = parseInt(el.css('padding-left'), 10);
        var rpad = parseInt(el.css('padding-right'), 10);

        el.css('padding-left', lpad+pad);
        total += lpad+pad;

        if ((total+rpad+pad) < difference) {
            el.css('padding-right', rpad+pad);
        } else {
            el.css('padding-right', Math.floor(rpad+pad));
        }
        total += rpad+pad;
    });
}
});

Adding the following to your CSS will clear the gap after the last menu item as well.

.menu li:last-child {
    margin:0;
}

EDIT: You should probably just change the right margin so it doesn't break any future margin changes.

.menu li:last-child {
    margin-right: 0;
}

Just remove float: left; from your .menu li rule. The reason is that floating the lis to the left is basically squashing them a bit -- they won't expand to the right even if they have space. Working version of your demo: little link.

Hope that helped!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!