Search code examples
htmlcssflexboxoverflow

text-overflow: ellipsis not working with flexbox


I created a table which consists out of div elements which all use display: flex. I also use display: flex on the cell element because I'm using other flex properties to center the text.

My problem is that the text in a cell of the table doesn't get shortened even tho it has text-overflow: ellipsis set in the css and is overflowing.

Removing display: flex from the cell element makes the text wrap and actually use text-overflow: ellipsis but I really want this to work with flexbox and I'm sure there is a solution for this.

.table {
  display: flex;
  flex-direction: column;
  width: fit-content;
  border: 1px solid #000;
}

.row {
  display: flex;
  height: 30px;
}

.row:not(:last-child) {
  border-bottom: 1px solid #000;
}

.cell {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-inline: 5px;
}

.cell:not(:last-child) {
  border-right: 1px solid #000;
}
<div class="table">
  <div class="row">
    <div class="cell"></div>
    <div class="cell">Column 1</div>
    <div class="cell">Column 2</div>
  </div>
  <div class="row">
    <div class="cell">1</div>
    <div class="cell">Text that is really long</div>
    <div class="cell">Text that is even longer than the really long one</div>
  </div>
  <div class="row">
    <div class="cell">2</div>
    <div class="cell">Text that is really long</div>
    <div class="cell">Text that is even longer than the really long one</div>
  </div>
  <div class="row">
    <div class="cell">3</div>
    <div class="cell">Text that is really long</div>
    <div class="cell">Text that is even longer than the really long one</div>
  </div>
</div>


Solution

  • text-overflow property only works on block containers. You can wrap the text in a separate element inside the cell and apply text-overflow: ellipsis to that element instead.

    ...
    .text-wrapper {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
    }
    
    ...
    <div class="cell">
      <div class="text-wrapper">
        Text that is even longer than the really long one
      </div>
    </div>