htmlcssoverflowtablecell

How do I get 2 table cells to be the same length with different amounts of text?


I am trying to create a key for a data table I made.

I want the key to be dynamically sized to take up the rightmost 20% of the screen. I also want all the table cells to be the same length and stretch across the entire key (20% /2 = 10% of the screen).

If the text is longer than 10% of the screen (or 50% of the table), I want it to be clipped at the end of the first line so that it doesn't distort the key.

I am going to style the empty td's in css and give them background colors, and the other td's will describe what that color represents in my data table (like a key on a map). My problem is, when I try to run this code, the empty td shrinks in order to show the text of the other td in the row.

How do I prevent this and force both of the td's to always be the same length?

.key {
  float: right;
  border-style: double;
  width: 20vw;
  white-space: nowrap;
  overflow: hidden;
}

.key td {
  width: 10vw;
  border: 1px solid #003C63;
}
<div class="key">
  <table>
    <tr>
      <td></td>
      <td> = all times</td>
    </tr>
    <tr>
      <td></td>
      <td> = some times</td>
    </tr>
    <tr>
      <td></td>
      <td> = no times</td>
    </tr>
  </table>
</div>


Solution

  • You have to set the width of the table (not the div wrapping it) and the table-layout: fixed style.

    I simplified your code by removing the div and add the key class directly to the table element.

    .key {
      float: right;
      border-style: double;
      width: 20vw;
      table-layout: fixed; /* <------- added */
      white-space: nowrap;
      overflow: hidden;
    }
    
    .key td {
      width: 10vw;
      border: 1px solid #003C63;
    }
    <table class="key">
      <tr>
        <td></td>
        <td> = all times</td>
      </tr>
      <tr>
        <td></td>
        <td> = some times</td>
      </tr>
      <tr>
        <td></td>
        <td> = no times</td>
      </tr>
    </table>

    For further explication, check out this Stack Overflow post: https://stackoverflow.com/a/17358739/6691953