Search code examples
csshtmlhtml-tablecolumn-width

How to give fixed width for the columns inside table in HTML?


P.S : Please don't mark as duplicate until you have read the entire question

I have a table where in I want to give fixed width to the columns as I want to display them dynamically. The width of the table is 100%. So in that table, only 1 column or 3 or 6, etc can be displayed. But the problem is if in a scenario I have only 1 column the data in that table occupies the entire 100% table even though i have given fixed width to the column. I want the column width to be fixed irrespective of the table width. Please guide where I am wrong. Below is the code I have been trying.

table {
  table-layout: fixed;
  word-break: break-all;
}
table td {
  border: 1px solid;
  overflow: hidden;
}
<table width="100%" cellspacing='0' cellpadding='0'>
  <col width="100px" />
  <col width="50px" />
  <col width="50px" />

  <tr>
    <th>First Column</th>
    <th>Second Column</th>
    <th>Third Column</th>

  </tr>
  <tr>
    <td>Text 1</td>
    <td>text 2</td>
    <td>text 3</td>

  </tr>
</table>


Solution

  • Add hidden column to the end of table.

    Table will be 100% width and resize hidden column than you resize the page.

    Code example:

    table
        {
            table-layout: fixed;
            word-break: break-all;
            border-collapse: collapse;
            width:100%;
        }
    td
        {
            height:50px;
            border: 1px solid;
        }
    th
        {
            height:50px;
            border: 1px solid;
        }
    .F
        {
            width:100%;
            border:none;
            border-left:1px solid;
        }
    <table>
          <col width='200px' />
          <col width='100px' />
          <col width='50px' />
          <tr>
                <th>First Column</th>
                <th>Second Column</th>
                <th>Third Column</th>
                <th class='F'></th>
          </tr>
          <tr>
                <td>Text 1</td>
                <td>text 2</td>
                <td>text 3</td>
                <td class='F'></td>
          </tr>
    </table>