Get ul width with floating li's using jQueryJavaScript - Stack Overflow

Say I have this<ul><li>Questions<li><li>Tags<li><li>Users<li&

Say I have this

<ul>
  <li>Questions</li>
  <li>Tags</li>
  <li>Users</li>
</ul>

ul { list-style: none }
li { float: left }

Basically, just like the menu above ("Questions Tags Users..." on the right of the Stackoverflow logo)

How do I get the actual width of the ul?

The purpose is so that I can align this ul to the right or centered.

Say I have this

<ul>
  <li>Questions</li>
  <li>Tags</li>
  <li>Users</li>
</ul>

ul { list-style: none }
li { float: left }

Basically, just like the menu above ("Questions Tags Users..." on the right of the Stackoverflow logo)

How do I get the actual width of the ul?

The purpose is so that I can align this ul to the right or centered.

Share Improve this question edited Oct 25, 2012 at 10:05 Ravichandran Jothi 3,06611 gold badges55 silver badges83 bronze badges asked Oct 25, 2012 at 9:57 AximiliAximili 29.5k57 gold badges162 silver badges227 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 3

Simply using width() will work in this case.

I assume though, given the nature of your question, you have applied display: inline to the ul so it's width cannot be read by the DOM.

In this case you can loop through the li elements and sum their widths like this:

var ulWidth = 0;
$("li").each(function() {
    ulWidth = ulWidth + $(this).width()
});
alert(ulWidth);

Example fiddle

To mimic a centered list you would need to find the width of both the UL and collective LI tags.

<!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis./ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script>
      jQuery(document).ready(function($){
        var w = 0;
        $('ul > li').each(function(){ w+= $(this).width(); });
        $('ul > li:first').css({'margin-left': ($('ul').width()-w)/2+'px'});
      });
    </script>
    <style type="text/css">
      ul,li { margin:0; padding:0; }
      ul { list-style: none }
      li { float: left; }
    </style>
  </head>
  <body>
    <ul>
      <li>Questions</li>
      <li>Tags</li>
      <li>Users</li>
    </ul>
  </body>
</html>

Well, try with jquery:

var width = $('ul').attr( 'width );

you could assign it a value like :

$('ul').attr( 'width' , value );

This should work for you:

$("ul").width()

You can use jquery .width() to get the width of your ul element

$('ul').width();

See Demo

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745228956a4617592.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信