How to truncate text with ellipsis in the middle based on container width?

Hi all! As the title states I want to truncate a long breadcrumb like text in the middle with ellipsis. ex Foo > Bar > ... > Baz . I have a solution by using a Resize observer on the element and then measuring the string size based on the font using canvas and then I truncate appropriately and update the elements textContent. This all works fine but I am afraid when I have a large list of these items that all need to be truncated I will have performance issues. So I was hoping someone here knows a better way to solve this. Markup is a list of possibly long text to truncate
<ol>
<li>Long text here</li>
</ol>
<ol>
<li>Long text here</li>
</ol>
6 Replies
reddogg476
reddogg4768mo ago
That sounds like it could work, depending the size of the breadcrumb container as the limiting factor. You'll likely want JavaScript. It might be easier to boil the list of elements down to an array, then limit the number of the elements in the array. If it goes over that number, then one of the list items becomes "...". Otherwise, all the elements are there. To resize smaller would mean to lower the max number of array elements.
Rax
RaxOP8mo ago
Hmm okay, still would use a Resize observer to react to the size change right? How bad of a performance hit would it be to have dozens of resize observers?
Squeemeister
Squeemeister8mo ago
Have you considered setting a max-width on the li elements? You could then truncate them using something like:
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
Also, just to clarify, are you only truncating based on the length of the <li> string or are you also truncating based on page-width or wrapper-width?
Rax
RaxOP8mo ago
Yeah the container for the lis have a max-width but I want the truncation of the ellipsis to be in the center of the string not where it overflows at the end of the content. Just on the length of the string overflowing its container. The max-width of it's container is 310px. But with window/screen size it can shrink down, but majority of the time it will be that 310px.
reddogg476
reddogg4768mo ago
CSS only may look like this: https://codepen.io/rhowell476/pen/dyLEzXg
reddogg476
reddogg4768mo ago
It's a start. It may be more preferred to always have a list element that the content can be "...", so there's always three lis. my version here goes down to two lis.
Want results from more Discord servers?
Add your server