Search code examples
htmlcssflexboxcontainer-queries

How to always truncate the last flex item in a flexbox container as the width of the container keeps reducing?


I have a case where I have a couple of flex items in a flex-box container. As the width of the container is reduced, I want the left item to not truncate and the right item to keep truncating until there's enough space for both the items. The right item should disappear if there's no more space left for it. See images below to understand the behaviour:

1

2

I was able to achieve the above behaviour by using flex-shrink: 0 on the left element. But the issue arises when I try to reduce the width of the container further and I am not able to get the left item to truncate by using the overflow and text-overflow properties. The item overflows the container due to the flex-shrink: 0 property which is needed to achieve the above behaviour when both the items are visible. How can I get the left item to truncate while still maintaining the above behaviour? An answer that can solve this for any number of flex-items would be great, I also appreciate an answer that can solve this for just 2 items.

3

Here's my code:

.flex-parent {
  width: 400px;
  display: flex;
  flex-wrap: nowrap;
  border: 1px solid red;
  padding: 10px;
  margin: 10px;
}

.child {
  margin: 0 10px;
  min-width: 0;
}

.no-ellipsis {
  flex-shrink: 0;
}

.ellipsis p {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
<div class="flex-parent">
  <div class="child no-ellipsis">
    <p>This is "fixed", don't truncate it!</p>
  </div>
  <div class="child ellipsis">
    <p>Lorem ipsum dolor sit amet, consectetur</p>
  </div>
</div>


Solution

  • Keep both the same but use a big flex-shrink value for the second one. Resize the below container for testing

    .flex-parent {
      width: 400px;
      display: flex;
      border: 1px solid red;
      padding: 10px;
      resize: horizontal;
      overflow: hidden;
    }
    :nth-child(2 of .child) {
      flex-shrink: 10000;
    }
    .child {
      margin: 0 10px;
      min-width: 0;
    }
    .child > p {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    <div class="flex-parent">
      <div class="child">
        <p>This is "fixed", don't truncate it!</p>
      </div>
      <div class="child">
        <p>Lorem ipsum dolor sit amet, consectetur</p>
      </div>
    </div>