Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize unknown number of elements to fill width of parent container

Tags:

css

I need to put an unknown number of divs (likely a limit of about 5) into a parent container and always make sure they remain equally divided. I'm not sure if this can be done with CSS alone but I figured I better ask. So if we know that 3 divs are used:

<style>
  .menu-button { 
    float: left;
    width: 33%;
  }
</style>
<div>
   <div class="menu-button">Button X</div>
   <div class="menu-button">Button Y</div>
   <div class="menu-button">Button Z</div>
</div>

Seems to work, but what if the number of .menu-button divs is unknown? Is there a better way to do it so it automatically adjusts horizontally?

like image 787
Anthony Hiscox Avatar asked Feb 09 '11 08:02

Anthony Hiscox


2 Answers

To do that with any element, you have two solutions:

  • make the browser simulating the table behavior
  • using Flexible Box layout

For instance, to build an horizontal menu, with equal width of every li elements, with this HTML code :

<div id="menu">
  <ul>
    <li><a href="#">First Element</a></li>
    <li><a href="#">Second Element</a></li>
    <li><a href="#">Third Element</a></li>
    ...
    <li><a href="#">N Element</a></li>
  </ul>
</div>

Using the table layout, CSS code would look like that:

#menu{
  width: 100%; /* for instance */
  display: table;
  table-layout: fixed;
}
#menu ul{
  display: table-row;
}
#menu ul li{
  display: table-cell;
}

Flexible Box layout is a more modern solution, and it's pretty widely supported nowadays:

#menu{
  width: 100%; /* for instance */
}
#menu ul{
  display: flex;
  flex-flow: row;
}
#menu ul li{
  flex-grow: 1;
}
like image 99
Capripot Avatar answered Oct 07 '22 09:10

Capripot


Unfortunatly I think you'll have to use tables to do this. As <td>'s resize itslef to fit into the full width.

HTH

like image 22
Chin Avatar answered Oct 07 '22 10:10

Chin