Search code examples
htmlcsshtml-table

CSS table-cell equal width


I have an indeterminate number of table-cell elements inside a table container.

<div style="display:table;">
  <div style="display:table-cell;"></div>
  <div style="display:table-cell;"></div>
</div>

Is there a pure CSS way to get the table-cells to be equal width even if they have differently sized content within them?

Having a max-width would entail knowing how many cells you have I think?


Solution

  • Here is a working fiddle with indeterminate number of cells: http://jsfiddle.net/r9yrM/1/

    You can fix a width to each parent div (the table), otherwise it'll be 100% as usual.

    The trick is to use table-layout: fixed; and some width on each cell to trigger it, here 2%. That will trigger the other table algorightm, the one where browsers try very hard to respect the dimensions indicated.
    Please test with Chrome (and IE8- if needed). It's OK with a recent Safari but I can't remember the compatibility of this trick with them.

    CSS (relevant instructions):

    div {
      display: table;
      width: 250px;
      table-layout: fixed;
    }
    
    div > div {
      display: table-cell;
      width: 2%; /* or 100% according to OP comment. See edit about Safari 6 below */
    }
    

    EDIT (2013): Beware of Safari 6 on OS X, it has table-layout: fixed; wrong (or maybe just different, very different from other browsers. I didn't proof-read CSS2.1 REC table layout ;) ). Be prepared to different results.