Need to set the width of a parent div dynamically based on the width of a ul
I've got a subnav on my site which is horizontal and I need to center it in the layout. Every subnav has a differnt number of elements so I need to calculate the width of the UL and then add it to the wrapping div so it will center properly.
Here is my html
<div id="subNav">
<ul id="navsub_761243_795431">
<li><a href="/Asset/RIA">Why Choose a RIA</a></li>
<li><a href="/Asset/HowWeOperate">How We Operate</a></li>
<li><a href="/Asset/ethicalinvesting">Ethical Investing</a></li>
<li><a href="/Asset/IndependentCustodian.htm">Independent Custodian</a></li>
<li><a href="/Quest/home">Insure Quest</a></li>
</ul>
</div>
Sometimes the above list will be 2 elements, sometimes 1, sometimes 6.
Here is the jQuery I was messing with. It sits within a document ready functio开发者_开发百科n.
$("#subNav").css("width", $("#subNav ul").children("li").innerWidth());
This will give me the width of one element, not the sum of all of them. Any help is greatly appreciated!.
Even though the previous answer is adequate. Just for reference, you have to specify the selector to get specific children. Then you could find the max value. However, this wouldn't get the width of the parent, but the max width of it's children.
You could specify with classes.
<ul class="level-1">
<li class="item-i">I</li>
<li class="item-ii">II
</ul>
http://api.jquery.com/children/
do it with css: http://jsfiddle.net/yW8mq/2/
edit: as you wrote in your comment you need to center the div also. So do the same thing i did to the UL to the div
You would use this to get the rendered width of the ul:
$("#subNav").css("width", $("#subNav ul:first").width() + "px");
Forgot the "px" at the end.
Explaination: The rendered width of the ul will be equal to the sum of all the list item widths and this will include any margin and padding adjustments for the list items. I don't believe jquery's .width() includes margin's or padding on the element you call it on (in this case the ul) so you may have to take that into account.
EDIT: Changed selector so that it will only select the first ul encountered which in this example would be the outer ul (in the case of nested lists)
This should do the trick: http://jsfiddle.net/nbzN3/
JS:
$.each($('.subNav ul').children(), function(i) {
computedWidth += $('.subNav ul').children().eq(i).outerWidth();
});
$('.subNav:visible ul').width(computedWidth+10);
HTML:
<div id="subNav1" class="subNav">
<ul id="navsub_761243_795431">
<li><a href="#">Nav 1-1</a></li>
<li><a href="#">Nav 1-2</a></li>
<li><a href="#">Nav 1-3</a></li>
<li><a href="#">Nav 1-4</a></li>
<li><a href="#">Nav 1-5</a></li>
</ul>
</div>
精彩评论