Casa Lim
Casa Lim

Reputation: 385

th's width in thead doesn't match td width of tbody

I want to empty the content of my table td, to make a loading and then show latest fetched data, but the problem is the thead seem have some flickering issue, as the width of thead is affected when tbody data is gone.

table {
  border-collapse: collapse;
}

table th,
table td {
  padding: 5px;
  border: 1px solid;
}

demo: https://jsfiddle.net/nLrpbz9r/1/

Upvotes: 2

Views: 3871

Answers (3)

Golnaz Saraji
Golnaz Saraji

Reputation: 154

I guess this two attribute which I set, we'll solve your problem:

table th,
table td {
  padding: 5px;
  border: 1px solid;
  width: 200px;
  text-align: center;
}

The last two lines fix the width of each td width the value you want ( Instead of 200 px and it's better to set it by percent value to support the responsibility) and the last line just put the text in center position. If you press the button, the Header cells will not change.

Upvotes: 0

Salman Arshad
Salman Arshad

Reputation: 272266

This is normal... display: none elements are not involved in table width calculation. You can use visibility: collapse instead:

$(function() {
  $('button').click(function() {

    const $tb = $("tbody");
    const new_visibility = $tb.css("visibility") === "visible" ? "collapse" : "visible";
    $("tbody").css({
      "visibility": new_visibility
    });

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button>Toggle tbody</button>

<table border="1">
  <thead>
    <tr>
      <th>name</th>
      <th>age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>john wesley</td>
      <td>18</td>
    </tr>
  </tbody>
</table>

Unfortunately... when you insert new data in tbody, the widths will change depending on content. There is no good solution except using a fixed layout table.

Upvotes: 1

Zeronull
Zeronull

Reputation: 261

add something like table th {min-width: 100px;} to your CSS.

$(function() {
  $('button').click(function() {
    const tb = $('tbody').clone()
    if ($(tb).length > 0) {
      $('tbody').hide()
    }
  })
})
table {
  border-collapse: collapse;
}

table th,
table td {
  padding: 5px;
  border: 1px solid;
}

table th {min-width: 100px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>name</th>
      <th>age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>john wesley</td>
      <td>18</td>
    </tr>
  </tbody>
</table>

<button>Hide tbody</button>

Upvotes: 0

Related Questions