开发者

Full width horizontal nav bar with evenly spaced items

开发者 https://www.devze.com 2023-04-10 09:44 出处:网络
Starting point: End point: I\'m trying to have a horizontal navigation bar that fills 100% of it\'s container. In the first example, you\'ll see all of the items aligned to the left. I\'m trying t

Starting point:

Full width horizontal nav bar with evenly spaced items

End point:

Full width horizontal nav bar with evenly spaced items

I'm trying to have a horizontal navigation bar that fills 100% of it's container. In the first example, you'll see all of the items aligned to the left. I'm trying to get it to fill the full width of the container as shown in the second example. I want the spacing between all of the items to be uniform (unlike the way it's s开发者_如何学Pythonhown, I just put that together quickly to give you an idea of what I'm trying to do). I need the text to not be an image and the container it goes in is fluid not fixed.


With a static number of elements it's easy - http://jsfiddle.net/X56cJ/

However, if you want to have uniform spacing between the text, not the elements themselves - it becomes tricky. Again, if the number of elements doesn't change, you do it with css classes and static widths. Otherwise it'll have to be javascript

EDIT: Here's the JavaScript way of getting same space between elements.

HTML:

<ul class="menu">
    <li>About Us</li>
    <li>Our Products</li>
    <li>FAQs</li>
    <li>Contact</li>
    <li>Login</li>
</ul>

JS:

function alignMenuItems(){
    var totEltWidth = 0;
    var menuWidth = $('ul.menu')[0].offsetWidth;
    var availableWidth = 0;
    var space = 0;

    var elts = $('.menu li');
    elts.each(function(inx, elt) {
        // reset paddding to 0 to get correct offsetwidth
        $(elt).css('padding-left', '0px');
        $(elt).css('padding-right', '0px');

        totEltWidth += elt.offsetWidth;
    });

    availableWidth = menuWidth - totEltWidth;

    space = availableWidth/(elts.length);

    elts.each(function(inx, elt) {
        $(elt).css('padding-left', (space/2) + 'px');
        $(elt).css('padding-right', (space/2) + 'px');
    });
}

Full example here


Using display: table on your parent, and display: table-cell on your children will do the trick. This is not supported in <= IE7.

http://codepen.io/simply-simpy/pen/jzski


If you know how many elements you'll have, you can specify a width of each element as a percent. Otherwise it won't be possible without resorting to tables or javascript.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号