HTML table 100% width, with vertical scroll inside tbody

by Denis Tverdokhlebov

HTML

<table class="mail_table fama_table_body">
  <thead>
    <tr>
      <th>Дата</th>
      <th>Кому</th>
      <th>Тема</th>
    </tr>
  </thead>
  <tbody class="color_table">
    <tr>
      <td>8.02.18</td>
      <td>Майа Рубинская</td>
      <td>Важные вопросы серьезных дел взрослых муж...</td>
      <td>.</td>
    </tr>
    <tr>
      <td>8.02.18</td>
      <td>Майа Рубинская</td>
      <td>Важные вопросы серьезных дел взрослых муж...</td>
      <td>.</td>
    </tr>
    <tr>
      <td>8.02.18</td>
      <td>Майа Рубинская</td>
      <td>Важные вопросы серьезных дел взрослых муж...</td>
      <td>.</td>
    </tr>
  </tbody>
</table>

CSS

table.fama_table_body {
  width: 100%;
  border-spacing: 0;
}

table.fama_table_body tbody,
table.fama_table_body thead {
  display: block;
}

thead tr th {
  height: 30px;
  line-height: 30px;
  /*text-align: left;*/
  /* text-align: center; */
}

table.fama_table_body tbody {
  height: 300px;
  overflow-y: auto;
  overflow-x: hidden;
}

tbody {
  border-top: 1px solid #bababa;
}

tbody td,
thead th {
  /* width: 20%; */
  text-align: center;
  padding: 15px 0;
  /* Optional */
  /* border-right: 1px solid black; */
}

.color_table tr:nth-child(odd) {
  background-color: #f3f3f3;
}

tbody td:last-child,
thead th:last-child {
  border-right: none;
}

tr td:first-child {
  text-decoration: underline;
}
/* 
.mail_table tr th:nth-child(1) {
  width: 180px;
}

.mail_table tr th:nth-child(2) {
  width: 250px;
}

.mail_table tbody tr td:nth-child(1) {
  width: 20% !important;
}

.mail_table tbody tr td:nth-child(2) {
  width: 30% !important;
} */

/* .mail_table tbody tr td:nth-child(3) {
    width: 100% !important;
} */

/* .mail_table tbody tr {
  width: 100% !important;
}
 */
 
 thead th {
  /* width: 20%; */
}
tbody td {
  /* width: 20%; */
}
thead th:nth-child(1) {
  width: 150px;
}
thead th:nth-child(2) {
  width: 250px;
}
thead th:nth-child(3) {
  width: 60%;
}

tbody td:nth-child(1) {
  width: 150px;
}
tbody td:nth-child(2) {
  width: 250px;
}
tbody td:nth-child(3) {
  width: 55%;
}
tbody td:nth-child(4) {
  width: 5%;
}

JavaScript

// Change the selector if needed
var $table = $('table.fama_table_body'),
  $bodyCells = $table.find('tbody tr:first').children(),
  colWidth;

// Adjust the width of thead cells when window resizes
$(window).resize(function() {
  // Get the tbody columns width array
  colWidth = $bodyCells.map(function() {
    return $(this).width();
  }).get();

  // Set the width of thead columns
  $table.find('thead tr').children().each(function(i, v) {
    $(v).width(colWidth[i]);
  });
}).resize(); // Trigger resize handler