Home > Mobile >  I have a flex box which contains two items to fit on one line in a confined space. How do I make rig
I have a flex box which contains two items to fit on one line in a confined space. How do I make rig

Time:10-06

I have a flex box div to fit in a limited space, it consists of two items, a category and someone's name. If the persons name is long, I want it to take preference and over the right hand end of the category (which can be hidden with overflow: hidden).

So for example I have this:

<div class="my-item">
  <div class="category">Supervisory Manager</div>
  <div class="name">Mrs Jacqueline Bennington-Smyth</div>
</div>

And I want the result to look like this all on one line

|Supervisory M Mrs Jacqueline Bennington-Smyth|

Even better would be this if possible

|Supervisor... Mrs Jacqueline Bennington-Smyth|

But for something less demanding of space

|Firefighter Decorated              John Smith|

Obviously totally contrived examples - but in the particular application I am working with even only 3 letters of the category will be enough, especially as a mouseover will bring up a small card with all the necessary details laid out in a better fashion.

I've been playing with flex-grow and flex-shrink, but I can't quite figure out how to achieve what I want

CodePudding user response:

You can go this way:

.my-item {
    display: flex;
    flex-direction: row;
    gap: 10px;
}
.my-item > div {
    white-space: nowrap;
}
.category {
    overflow: hidden;
    text-overflow: ellipsis;
}
.name {
    flex-grow: 1;
    text-align: right;
}
<div class="my-item">
  <div class="category">Supervisory Manager</div>
  <div class="name">Mrs Jacqueline Bennington-Smyth</div>
</div>

And play on JSFiddle.

  • Related