Search code examples
cssbootstrap-4responsivecss-tables

How to make fixed column headers sit at the bottom of the header row


I have a responsive table with the first two columns fixed and the rest floating. My questions are:

  1. Why do the headers for the first two columns float to the top of the header row, while the rest stick to the bottom?
  2. How do I fix it so that they all stick to the bottom?

enter image description here

Fiddle

HTML

<div class="container">
  <div class="table-responsive">
    <table class="table" style="table-layout: auto; width: auto">
      <thead>
        <tr>
          <th>A</th>
          <th>B</th>
          <th>Floating</th>
          <th>Floating</th>
          <th>Floating</th>
          <th>Floating</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>foo</td>
          <td>bar</td>
          <td>baz</td>
          <td>999 Acacia Avenue</td>
          <td>Some longish text value</td>
          <td>Another longish text value</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

CSS

.table > thead:nth-child(1) > tr:nth-child(1) > th:nth-child(1) {
    position: absolute;
    width:30px;
    left:0px;
}
.table > thead:nth-child(1) > tr:nth-child(1) > th:nth-child(2) {
    position: absolute;
    width:60px;
    left:30px;
}
.table > thead:nth-child(1) > tr:nth-child(1) > th:nth-child(3) {
    padding-left:30px;
}
.table > tbody > tr > td:nth-child(1) {
    position: absolute;
    width:30px;
    left:0px;
}
.table > tbody > tr > td:nth-child(2) {
    position: absolute;
    width:60px;
    left:30px;
}
.table> tbody > tr > td:nth-child(3) {
    padding-left:30px;
}
th {
    height: 100px;
}
td {
    white-space: nowrap;
}

Solution

  • When you absolutely position a table cell it stops acting like a table and things like vertical-align: bottom tend to stop working... You can fix it by using flexbox.

    Also you're being extremely specific with your selectors > and nth-child(1). That makes it more difficult to track down the issues. I removed a bunch of that and added flexbox to push things down.

    Here's the fiddle

    th:nth-child(1), th:nth-child(2) {
        position: absolute;
        width:30px;
        left:0px;
        display:flex;
        flex-direction:column;
        justify-content: flex-end;
    }
    th:nth-child(2) {
        width:60px;
        left:30px;
    }
    th:nth-child(3) {
        padding-left:30px;
    }
    td:nth-child(1), td:nth-child(2) {
        position: absolute;
        width:30px;
        left:0px;
    }
    td:nth-child(2) {
        width:60px;
        left:30px;
    }
    td:nth-child(3) {
        padding-left:30px;
    }
    th {
        height: 100px;
    }
    td {
        white-space: nowrap;
    }