Chunky Chunk
Chunky Chunk

Reputation: 17217

CSS Flexible Table Headers

I'm having trouble shrinking the width of the .rowHeader1 when the table is resized.

.rowHeader1 and .rowHeader2 are wrapped within a flex container. .rowHeader1 should grow and shrink but should never be smaller than 60px in width while .rowHeader2 should always remain 60px in width.

Without removing the Table semantic tags, is it possible to make the row headers flex properly?

body {
    background-color: #444;
}

table {
    border: 1px solid white;
    color: white;
    width: 100%;
}

tr, th, td {
    border: 1px solid white;
}

tbody td {
    white-space: nowrap;
}

tbody th {
    display: flex;
}

:root {
    --MIN-SIZE: 60px;
}

.rowHeader1 {
    flex: 1 1 var(--MIN-SIZE);
    border: 1px solid red;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    text-align: left;
}

.rowHeader2 {
    flex: 0 0 var(--MIN-SIZE);
    border: 1px solid red;
}
<table>
    <thead>
        <tr>
            <th>Column Header</th>
            <th>Data</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>
                <div class="rowHeader1">Row Header 1 Row Header 1</div>
                <div class="rowHeader2">RH 2</div>
            </th>
            <td>
                Some Table Data Some Table Data Some Table Data
            </td>
        </tr>
    </tbody>
</table>

Upvotes: 0

Views: 423

Answers (1)

Dan Knights
Dan Knights

Reputation: 8368

If you set the flex-shrink value of .rowHeader1 to 0 and set it's width to 60px, it will grow to fill the space but won't shrink smaller than 60px:

body {
  background-color: #444;
}

table {
  border: 1px solid white;
  color: white;
  width: 100%;
}

tr,
th,
td {
  border: 1px solid white;
}

tbody td {
  white-space: nowrap;
}

tbody th {
  display: flex;
}

:root {
  --MIN-SIZE: 60px;
}

.rowHeader1 {
  flex: 1 0 var(--MIN-SIZE);
  width: 60px;
  border: 1px solid red;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}

.rowHeader2 {
  flex: 0 0 var(--MIN-SIZE);
  border: 1px solid red;
}
<table>
  <thead>
    <tr>
      <th>Column Header</th>
      <th>Data</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>
        <div class="rowHeader1">Row Header 1 Row Header 1</div>
        <div class="rowHeader2">RH 2</div>
      </th>
      <td>
        Some Table Data Some Table Data Some Table Data
      </td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Related Questions