1

I have a simple HTML table as below.

This is a responsive table and shrinks down when the browser is shrunk.

I want to set the minimum width of the column to be as wide as the header text.

What is the best way to do this in CSS?

       <table>
       <thead class="ui-datatable-thead">
           <tr class="ui-state-default">
               <th class="ui-state-default">COL HEADER</th>
           </tr>
       </thead>
       <tbody class="ui-datatable-data ui-widget-content">
          <tr class="ui-widget-content ui-datatable-odd">
              <td>DATA</td>
          </tr>
       </tbody>
       </table>

I have looked at some other answers but haven't found a solution yet.

Ben Cameron
  • 4,335
  • 6
  • 51
  • 77
  • Take a look here, maybe this helps http://stackoverflow.com/questions/570154/html-table-keep-the-same-width-for-columns – vadber Mar 17 '17 at 12:37

2 Answers2

0

table {
    display: table;
    width: 100%;
    table-layout: fixed;
    margin-bottom: 20px;
}

th,td {
    display: table-cell;
    border: 1px dotted red;
    padding: 4px 6px;
    width: 2%;
    margin-bottom: 0;
}
<table>
       <thead class="ui-datatable-thead">
           <tr class="ui-state-default">
               <th class="ui-state-default">COL HEADER 1</th>
               <th class="ui-state-default">COL HEADER 2</th>
               <th class="ui-state-default">COL HEADER 3</th>
           </tr>
       </thead>
       <tbody class="ui-datatable-data ui-widget-content">
          <tr class="ui-widget-content ui-datatable-odd">
              <td>DATA 1</td>
              <td>DATA 2</td>
              <td>DATA 3</td>
          </tr>
       </tbody>
       </table>

All you need to set the cell width th & td table-layout to 'fixed'.Just like i mentioned in css code. If total size of table is 500px and there are 5 columns then each column will have 100px.

table{
    border: 1px solid black;
    table-layout: fixed;
    width: 500px;
}

th, td {
    border: 1px solid black;
    width: 100px;
}
Irfan Muhammad
  • 715
  • 2
  • 8
  • 20
  • 1
    Thanks for this. What if I don't know the column widths but want it to set as the width of the header text which could vary? – Ben Cameron Mar 17 '17 at 13:07
0

You need to fix the size of the heading's TD. so body's TD will automatically take width as applied in heading's TD.

Rohan
  • 467
  • 2
  • 11