How do I make all items in a menu equal in size regardless of quantity?

Asked

Viewed 1,759 times

5

I want to make a menu that always leaves the items with proportional sizes, occupying all the available width and adapting.

.top-menu ul {
  width: 100%;
}

.top-menu ul li {
  display: inline;
  list-style: none;
}

.top-menu ul li a {
  display: inline-block;
}
<div class="top-menu full">
  <ul>
    <li><a>Home</a></li>
    <li><a>Aqui!</a></li>
    <li><a>Alí!</a></li>
    <li><a>Acolá!</a></li>
    <li><a>Mais Pra lá</a></li>
    <li><a>Não sei onde</a></li>
  </ul>
</div>

  • 1

    Ready Sergio, I restored.

4 answers

4

Define display:table-cell; for li’s, so will behave as cedulas of tables and consequently fill all available space.

1


To achieve this you have to give display: table; at the ul and display:table-cell; at the li.

Test like this:

.top-menu ul {
    width: 100%;
    display: table;
}

.top-menu ul li {
    display:table-cell;
    list-style: none;
}

Example

Another option in case you know how many li have can use so on .top-menu ul li {:

float: left;
width: 16%; // neste caso (100% / 6 links) = 16%

Example

-2

Why not try dynamically using jQuery? For example, you can get the number of list items at runtime and divide the total width by that value by assigning the result to the width of each item in your list, something similar to the following code snippet:

var seletorDosItens = $(".top-menu full").find("li");
var totalDeItensDaLista = seletorDosItens.length;
seletorDosItens.css("width", (100 / totalDeItensDaLista) + "%");
  • 1

    But if your layout is responsive, there will be problems unless you add events to update as the viewport changes, and these in turn would influence performance. I would still strongly recommend using CSS.

  • I think to mess with styling the more css the better.

  • Ulysses, your code worked, I just had to take out "full" of $(".top-menu") and already left added the float in css.

  • Diego, good observation, but the menu can be hidden to appear with a click on an icon. Thus would be made a great change of look and space. Note: I never did, but I imagine it’s like this

-2

Add float: left nas li.

And with jQuery have the following code:

<script>

    $(document).ready(function() {
        $('.top-menu li').css("width", ($('.top-menu ul').width() / $('.top-menu ul li').size()) + "px");

        $( window ).resize(function() {
            $('.top-menu li').css("width", ($('.top-menu ul').width() / $('.top-menu ul li').size()) + "px");
        });
    });

</script>

But I think the best way is the one @Diegolopeslima quoted with css

display:table-cell;

nas li.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.