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.
4 Answers
Reset to default 3Simply 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条)