Search code examples
htmlcss

Make buttons the same width without specifying the exact size


I have five buttons. I want them to take up the available width of their parent div, each being equally sized:

<div style="width: 100%; background-color: red;">
    <button type="button" style="width: 20%;">A</button>
    <button type="button" style="width: 20%;">B</button>
    <button type="button" style="width: 20%;">C</button>
    <button type="button" style="width: 20%;">D</button>
    <button type="button" style="width: 20%;">E</button>
</div>

Is there a way I can do this without having the manually figure out that they each require 20% width? I want to remove a button at runtime, and that means I have to go and update each remaining button again to width=25%.

I am just checking if there's a more automated way of doing it.


Solution

  • The simplest way, and the most robust way, is to use a table:

    <style>
    .buttons { 
      width: 100%;
      table-layout: fixed;
      border-collapse: collapse;
      background-color: red; 
    }
    .buttons button { 
      width: 100%;
    }
    </style>
    <table class=buttons>
     <tr>
        <td><button type="button">A</button>
        <td><button type="button">B</button>
        <td><button type="button">C</button>
        <td><button type="button">D</button>
        <td><button type="button">E</button>
    </table>
    

    (This won’t improve your reputation among colleagues these days if they see your code, though it actually solves the problem probably better than any alternative. So you might consider doing the next best thing: use div markup and display: table etc. Fails on old browsers that don’t support such CSS features.)