Search code examples
javascripthtmlcsshtml-tablecss-tables

Align Body from Header of Table after inserting values on table body


Problem :

  • The contents of the table body are not aligned with the header of each column of the table.

Code :

var test_insert1 = '<tr>' +
  '<td  class="td-trad-9">762261</td>' +
  '<td  class="td-trad-7">1.16176</td>' +
  '<td class="td-trad-8">1.1618</td>' +
  '<td class="td-trad-1">2018-08-08</td>' +
  '<td class="td-trad-2">03:32</td>' +
  '<td class="td-trad-3">This is a test long value</td>' +
  '<td class="td-trad-4">1.00</td>' +
  '<td class="td-trad-5">Up</td>' +
  '<td class="td-trad-6">0.80</td>' +
  '</tr>'+
  '<tr>' +
  '<td  class="td-trad-9">456985</td>' +
  '<td  class="td-trad-7">1.65476</td>' +
  '<td class="td-trad-8">1984218</td>' +
  '<td class="td-trad-1">2018-08-08</td>' +
  '<td class="td-trad-2">03:32</td>' +
  '<td class="td-trad-3">This is a test value</td>' +
  '<td class="td-trad-4">10000</td>' +
  '<td class="td-trad-5">Up</td>' +
  '<td class="td-trad-6">1.00</td>' +
  '</tr>';

$('#add').click(function() {
  $('#new_table_test_body').html(test_insert1);
});
#new_table_test {
  width: auto;
  table-layout: fixed;
  border-collapse: collapse;
  /* color:white; */
  text-align: center;
  vertical-align: middle;
}

#new_table_test tbody::-webkit-scrollbar {
  width: 0px;
  /* remove scrollbar space */
  background: transparent;
  /* optional: just make scrollbar invisible */
}

#new_table_test tbody {
  display: block;
  width: 100%;
  overflow: auto;
  height: 100px;
}

#new_table_test thead tr {
  display: block;
}

#new_table_test thead {
  background: black;
  color: #fff;
}

#new_table_test th,
#new_table_test td {
  padding: 5px;
  text-align: left;
  width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="new_table_test">
  <thead id="new_table_test_header">
    <tr>
      <th>Header 1</th>
      <th>Header Two</th>
      <th>Head Three</th>
      <th>H4</th>
      <th>Header 5</th>
      <th>Heads 6</th>
      <th>Header seven</th>
      <th>Header 8</th>
      <th>Header Nine</th>
    </tr>
  </thead>
  <tbody id="new_table_test_body"></tbody>
</table>

<button id="add"> Add Details </button>

-- EDIT --

Additional:

Conditions:

  • Scrolling of table body is possible
  • Header is not affected by scrolling (fixed)
  • Width should auto adjust based on content

Here is also an updated fiddle for my concern: http://jsfiddle.net/9sjyvb5w/50


Solution

  • Change this :

    #new_table_test {
      width: auto;
      table-layout: fixed;
    }
    

    To this :

    #new_table_test {
      width: 1000px;
      table-layout: auto;
    }
    

    Also you should remove display: block; from #new_table_test tbody and #new_table_test thead tr.

    There is more info here about table-layout Property.

    jsffiddle

    jsfiddle with scroll

    jsfiddle with fixed header