Truncate longer text-chips before shorter will be truncated

55 Views Asked by At

I have a list of countries, i.e., Afghanistan, Chile, Saint Vincent and the Grenadines. They all are placed in a chip with a max-width. If the length of the list reaches the max-width, the country names should be truncated with ellipses. This means the country Saint Vincent and the Grenadines should be truncated first and Chile last.

So the question is, how to resize longer elements first before shorter will be resized? If shorter elements reach their needed space, the longer elements can use the rest of the space, with pure CSS.

I tried it with flex-box but in this case all countries will be truncated based on their width ratio. I also tried to give all countries the same width, but shorter countries have empty space at the end.

Here's the current result: Current Result

Here's my code:

<div class="chip">
  <div class="criteria">Country</div>
  <div class="items">
    <div class="item"><p class="name">United Kingdom</p></div> 
    <div class="item"><p class="name">Saint Vincent and the Grenadines</p></div>
    <div class="item"><p class="name">Chile</p></div> 
  </div>
</div>

/* CSS */
.criteria:after { content: ":"; }

.items {
  margin-left: 4px;
  display: flex;
  max-width: 220px;
}

.item {
  min-width: 0; display: flex;
  
  .name {
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin: 0; padding: 0;
  }
  &:after {
    content: ","; padding-right: 4px;
  }
  &:last-child:after { content: "" }
}

You can see a more advanced example on Codepen: https://codepen.io/Densagined/pen/wvNNwbz

0

There are 0 best solutions below