Cristi
Cristi

Reputation: 531

How can I give dynamic width for ul

I wish to give width (ul) to dynamically depending on how many elements there are in the list.

What is wrong what they are doing?

I have this sample: link

$('.sub-menu').each(function() {
  var liItems = $(this);
  var Sum = 0;
  if (liItems.children('li').length >= 1) {
    $(this).children('li').each(function(i, e) {
      Sum += $(e).outerWidth(true);
    });
    $(this).width(Sum + 1);
  }
});
.sub-menu {
  background: red;
  display: block;
  overflow: auto;
}
.sub-menu li {
  width: 25%;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="sub-menu">
  <li>menu1</li>
  <li>menu2</li>
  <li>menu3</li>
  <li>menu4</li>
</ul>

<ul class="sub-menu">
  <li>menu1</li>
  <li>menu2</li>
</ul>

Upvotes: 1

Views: 1309

Answers (2)

Mikal Schacht Jensen
Mikal Schacht Jensen

Reputation: 547

If you want the items to be exactly 25% of the page width, it gets a little tricky using css only. But I'm pretty sure your goals can be achieved without resorting to javascript.

One way is to fake it, by putting the background color on the <li> elements instead of the <ul>, and removing space between them. Technically, the list is still the full width of the page, as ilustrated by the border, so this solution wont work it that is a problem.

.sub-menu {
  display: block;
  padding: 0;
  margin: 0 0 10px 0;
  border: dashed 1px grey;
}
.sub-menu:after {
  display: block;
  content: '';
  clear: both;
}
.sub-menu li {
  background: red;
  list-style: none; /* hides the bullet */
  width: 25%;
  float: left;
}
<ul class="sub-menu">
  <li>menu1</li>
  <li>menu2</li>
  <li>menu3</li>
  <li>menu4</li>
</ul>
<ul class="sub-menu">
  <li>menu1</li>
  <li>menu2</li>
</ul>

If, however, you can accept a fixed witdth on the <li> elements, like width: 200px then andreas' suggested answer is a better and cleaner solution.

Upvotes: 1

andreas
andreas

Reputation: 16936

You can just use display: inline-block; on your <ul> and on your list elements (no need for floating):

.sub-menu {
  background: red;
  display: inline-block;
  padding: 0
}
.sub-menu li {
  display: inline-block;
}
<ul class="sub-menu">
  <li>menu1</li>
  <li>menu2</li>
  <li>menu3</li>
  <li>menu4</li>
</ul>
<br />
<ul class="sub-menu">
  <li>menu1</li>
  <li>menu2</li>
</ul>

Upvotes: 2

Related Questions