Why does not the width on the td element work with the corrected table layout?

advertisements

I have read many post on SO about this, e.g. TD column width value not working with fixed table-layout td widths, not working? etc. But still when I give width to td it doesn't get that width. Here is a working example of the problem:

div {
  width: 400px;
  padding: 5px;
  border: 1px solid red;
}
table {
  table-layout: fixed;
  width: 100%;
  border: 1px dotted green;
}
td {
  word-break: break-all;
}
td:nth-of-type(1) {
  width: 50px;
}
td:nth-of-type(2) {
  width: 150px;
}
<div style="width: 400px;">
  <table style="table-layout: fixed; width: 100%;">
    <thead>
      <tr>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <tr class="odd">
        <td class="">
          <a href="#">The_first_line</a>
        </td>
        <td class="">
          <a href="#">The_second_but_a_long_line_with_so_many_characters</a>
        </td>
        <td class="">
          <ul class="">
            <li class=""><a href="#" rel="tag" title="" class="">The simple</a>
            </li>
          </ul>
        </td>
        <td>
          <a href="#">last</a>
        </td>
      </tr>
    </tbody>
  </table>
</div>

The first td should have taken 50px and the second should have taken 150px, but this is not happening. Why?


Your pseudo :second-of-type is invalid. Try :nth-of-type() instead:

td:nth-of-type(2) {
  width: 150px;
}

However this isn't a very robust way of targetting your element. What if you have multiple tables on your page. It might be a good idea to add a class to your table:

<table class="my-table">

And then target specific for that table:

.my-table td:nth-of-type(2) { .. }