Nithin Viswanathan
Nithin Viswanathan

Reputation: 3283

How to resize the horizontal menu with respect to its li?

I have 7 menus in my code.Sometimes it may be 6 based on the usertype.If admin is entered it will be 7.User may have only 6 menus. How can resize the menu dynamically. For that I used the code

<div id="menu">
<ul>
<li><a href="#">home1</a></li>
<li><a href="#">home2</a></li>
<li><a href="#">home3</a></li>
<li><a href="#">home4</a></li>
<li><a href="#">home5</a></li>
<li><a href="#">home6</a></li>
<li><a href="#">home7</a></li>
</ul>
</div>

How can I do this with jquery?

EDIT

$(document).ready(function() {
    if ( $('#menu ul li').length > 6 ) {
        $('#menu ul li').css('width','14.5%'); 
    }
    else
    {
        $('#menu ul li').css('width','16.6%'); 
    }
});
    }
});

Upvotes: 1

Views: 797

Answers (3)

Carlos Martinez T
Carlos Martinez T

Reputation: 6528

Instead of table cells use display inline-block:

#menu { display: inline-block;background:#000; }
#menu ul { display: inline-block; margin:0;padding: 0; }
#menu ul li { display: inline-block; margin:0; padding: 0;}
#menu ul li a { display: inline-block; padding: 10px; color: #fff;}
#menu ul li a:hover { color: #ff0;}

Fiddle here: http://jsfiddle.net/BtvY9/

Upvotes: 1

Michael
Michael

Reputation: 7092

Assuming hexblot's answer isn't what you wanted and you want to distribute LI's of a varying width across the width of a container element, without the LI's necessarily taking up the full-width of your navigation bar then use this:

http://jsfiddle.net/sxGMZ/

#menu ul {
    display: block;
    text-align: center;
    width: 100%;
    background: brown;
}

#menu ul li {
    display: inline-block;
    height: 30px;
    padding: 10px 12px 0 12px;
    background: #ccc;
}

Upvotes: 1

Nick Andriopoulos
Nick Andriopoulos

Reputation: 10643

Assuming that the desired outcome is for the above menu to be rendered in one line, regardless of the exact number of items -

the best way to do this would be with tables, as they have native behavior for this type of thing ( taking up a long line and distributing items evenly over it ). The good thing is that we can easily fake that behavior using

#menu { display: table; width: 100%; }
#menu ul { display: table-row; }
#menu ul li { display: table-cell; }

this will automatically distribute your <li>s over a long line, using the containers width.

You can also see a jsFiddle with an example of the above.

Upvotes: 5

Related Questions