Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Table, first and last column fixed width and columns between dynamic, but equal width

Tags:

html

css

Is it possible to have a table with width 100% (so the table fits the screen size), where the first and the last column have a fixed width, and the columns between take the rest, both 50%.

Like:

+--------------------+--------------------------------------+--------------------------------------+------------+
| width:300px;       | with dynamic, equals next column     | width dynamic, equals prevous column | width:50px;|
+--------------------+--------------------------------------+--------------------------------------+------------+
+--------------------+--------------------------------------+--------------------------------------+------------+
+--------------------+--------------------------------------+--------------------------------------+------------+
+--------------------+--------------------------------------+--------------------------------------+------------+
like image 690
thobens Avatar asked Jul 29 '11 11:07

thobens


2 Answers

Try this:

As you can see the two centre column remain equal sized, due to the table-layout:fixed, even when the content is of different length. Try adding more and less content to the two centre columns.

JSFiddle: http://jsfiddle.net/RtXSh/

CSS

table {
    width:100%;
    border-collapse:collapse;
    table-layout:fixed; 
}

td {
    border: 1px solid #333;
}

HTML

  <table>
    <tr>
      <td style="width:300px;">
        test
      </td>
      <td>
        test test tes test test
      </td>
      <td>
        test
      </td>
      <td style="width:50px;">
        test
      </td>
    </tr>
  </table>
like image 131
Bazzz Avatar answered Sep 25 '22 05:09

Bazzz


Try using the pseudo element first-child and last-child

If I'm not mistaken the other columns will align equally by themselves. You might need to use the !important statement behind the first-child and last-child widths.

table{ table-layout: fixed; width: 100%; }
td { border: 1px solid black; }
td:first-child{ width: 100px; }
td:last-child{ width: 100px; }
<table>
    <tr>
      <td>100px</td>
      <td>some text</td>
      <td>some text</td>
      <td>100px</td>
    </tr>
</table>

However, as nurettin pointed out, if you use a thead and tbody section you have to style the header. Styling the td:first-child and td:last-child will not work.

table{ table-layout: fixed; width: 100%; }
td { border: 1px solid black; }
th:first-child{ width: 100px; }
th:last-child{ width: 100px; }
<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
      <th>Column 4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>100px</td>
      <td>some text</td>
      <td>some text</td>
      <td>100px</td>
    </tr>
  </tbody>
</table>
like image 45
Gilles Lesire Avatar answered Sep 26 '22 05:09

Gilles Lesire