0

I have a case which I'm trying to solve with pure CSS, but I somehow feel like it is not possible (or at least not without using tables).

Imagine following layout

<div class="parent"> <span class="name"> Some name </span> <span class="number"> 123 </span> </div> 

I want the parent to be of a fixed width and then have name followed inline by number. However, if the name is too long, I would like it to truncate (using ellipsis), but the number should remain and be moved to the right until it reaches the border of parent.

Here are few examples to illustrate.

Short text 1 | Longer text 12 | Very, very lon..123| 

Notice that also the number text can have variable length (thus the width can't be fixed).

Any ideas?

1 Answer 1

1

CSS Flexbox layout does a good job of making this sort of thing a breeze. You can read about the details on using it on the MDN article "Using CSS Flexible Boxes", but here is a simple example of how it can solve your layout:

.parent { display: flex; width: 8em; } .name { /* Make width shrinkable beyond width of content */ flex: 0 1 auto; /* Make sure text doesn't wrap or push beyond element boundaries */ overflow: hidden; white-space: nowrap; /* Show an ellipsis when text cuts off */ text-overflow: ellipsis; } .number { /* Make width inflexible */ flex: 0 0 auto; } 

You can see it in action in this example JSBin.

Sign up to request clarification or add additional context in comments.

2 Comments

Suggestion of edit: Please add flex: 0 1 auto to .name and flex: 0 0 auto to .number to be more flex-box standard.
Thanks, this works exactly like I wanted it. I guess I should finally look into the felx-box feature. However, pity it's only supported on the most modern browsers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.