Search code examples
htmlcsstextellipsis

Can't enable ellipse character on long text not fitting the cell in a table


I want an ellipsis to appear whenever the text gets cut off when the width of the table cell is too narrow to display it. According to CSS Tricks, it's supposed to look as below (nothing surprising there).

td {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

However, I can't make it work. First I thought it was because I'm applying Bootstrap and there might be some styling poofing my approach but then I tried to reproduce the error in an isolated fiddle and - tada! - I got it working. (I.e. I got it to fail ellipting, hence got the reproducible error to succeed occurring.)

The fiddle is here. What am I missing?!


Solution

  • Solution 1

    Table cells don't handle overflow well. You will need to set the max-width CSS property on each td for the overflow to work. Try to make use of max-width instead of width

    The max-width CSS property sets the maximum width of an element. It prevents the used value of the width property from becoming larger than the value specified by max-width.

    body {
      font: 13px Verdana;
    }
    
    td {
      background-color: pink;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 50px;
    }
    <table class="table">
      <thead>
        <th>Name</th>
        <th>Alias</th>
        <th>Location</th>
        <th>Updated</th>
        <th>Actions</th>
      </thead>
      <tbody>
        <tr>
          <td>Ali Baba &amp; Co.</td>
          <td>Boys 'n da hood</td>
          <td>Somewhere over the rainbow</td>
          <td>February 30th</td>
          <td>Do stuff!</td>
        </tr>
      </tbody>
    </table>

    Solution 2

    Or Just place the td content inside <span> and then apply the css

    body {
      font: 13px Verdana;
    }
    
    span {
      background-color: pink;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 100%;
      display: block;
    }
    
    .table {
      width: 100%;
      table-layout:fixed;
    }
    <table class="table">
      <thead>
        <th>Name</th>
        <th>Alias</th>
        <th>Location</th>
        <th>Updated</th>
        <th>Actions</th>
      </thead>
      <tbody>
        <tr>
          <td><span>Ali Baba &amp; Co.</span></td>
          <td><span>Boys 'n da hood</span></td>
          <td><span>Somewhere over the rainbow</span></td>
          <td><span>February 30th</span></td>
          <td><span>Do stuff!</span></td>
        </tr>
      </tbody>
    </table>