Hi. I have a CSS menu based on a flattened un-ordered list (UL), as follows:

<ul class="tabbed"> 
    <li class="current_page_item" > 
        <a href="/">Home</a> 
    </li> 
    <li  > 
        <a href="/News">News</a> 
    </li> 
    <li  > 
        <a href="/About">About Us</a> 
    </li> 
    <li  > 
        <a href="/Products">Products</a> 
    </li> 
    <li  > 
        <a href="/Contact">Contact Us</a> 
    </li> 
</ul> 

I've managed to center the menu in it's parent container using the following CSS:

ul.tabbed 
{
     margin:auto;
     padding:0;
     width:650px;
}

However, the above menu is dynamically created, and the number of menu items could change depending on page requests and what area of the site a user is currently on. So using 650px doesn't center it all the time. So my guess is that I would need to set the width property dynamically via Javascript. How would I go about this using JQuery?

I was thinking of setting each menu item to be a fixed width (say 100px) and then setting the width of ul.tabbed to be X * 100px where X is the number of list items in the unordered list.

Is this the right approach, and how would one implement it using Jquery? Is there a way to do it without setting a fixed width?

2 answers

0
points
This was chosen as the best answer

I got it working by using the following code:

<script type="text/javascript">
    $(document).ready(function() {
        $("ul.tabbed").css("width", $("ul.tabbed").children("li").size() * 115);
    });
</script>

I also set the CSS as follows:

ul.tabbed {
    margin:auto;
    padding: 0;
}
ul.tabbed li {
    float: left;
    list-style: none;
    width:110px;
} 

I set the width of ul.tabbed li to be 110px, and in the JavaScript just set the width of ul.tabbed = the number of li children * 110px + 5px for padding.

Worked like a charm.

Thanks to Dan for pointing me in the right direction.

Answered almost 7 years ago by Saajid Ismail
danwellman 5600
2
points

A jQuery approach should be relatively simple:

Take the width out of the CSS declaration (or set the width to be what you know to be the minimum width) and give the nav menu an id (as an id selector is faster than a class selector when selecting elements with jQuery)

Then use something like:

$(function(){
    $("#nav_menu_id").css("width", $("#nav_menu_id").width());
});

This will set the width using a style attribute on the nav element, using the computed width of the navigation menu (this doesn't include borders, margins, or padding).

The auto margin should then center the navigation menu.

Answered almost 7 years ago by danwellman
  • The above code doesn't work. $("#nav_menu_id").width() either returns the full width of the parent container less padding, or the width I set in the CSS doc. It's not reading the value I need - which is the actual length. I think it needs to be calculated somehow? Saajid Ismail almost 7 years ago