Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent truncating items at the same time

I am trying to solve a problem where I have 3 items in a row and when resizing window I wanna first to truncate second item and after its at minWidth then start truncating first item. Currently all items are truncating at the same time.

.container {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 10px;
}

.child {
  border: 1px solid;
  height: 40px;
}

.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis
}

.btn {
  min-width: 30px
}

.label {
  overflow: hidden
}
<div class="container">
  <div class="child label">
    <h3 class="truncate">Item label</h3>
  </div>
  <div class="child btn truncate">
    Item Button
  </div>
  <div class="child">
    Item Status
  </div>
</div>

https://jsfiddle.net/e08m4Lcp/

like image 378
rtom Avatar asked Sep 05 '25 08:09

rtom


1 Answers

TL;DR If you need to favor 1 child shrinking over another inside a flex parent, you can use the flex-shrink CSS property. If you'd rather read a more official explanation, here's the MDN docs for flex-shrink

Solution In your example, adding flex-shrink: 9999; to .btn will make that component shrink exclusively, until it hits its min-width.

Sample

div {
  gap: 10px;
  display: flex;
  white-space: nowrap;
}

p:nth-child(1) {
  overflow: hidden;
  text-overflow: ellipsis;
}

p:nth-child(2) {
  overflow: hidden;
  text-overflow: ellipsis;
  flex-shrink: 999999;
  min-width: 50px;
}
<div>
  <p>Lorem ipsum dolor sit amet
  <p>Lorem ipsum dolor sit amet
  <p>Lorem ipsum
</div>

Explanation

flex-shrink works as a ratio of all values. So if you have 2 elements, flex-shrink: 1 and flex-shrink: 2 next to one another, the 2 will shrink twice as fast as the 1.

In order to achieve your desired result, simply set an arbitrarily large value, like flex-shrink:9999 on an item so it will shrink exclusively (until other properties like min-width stops it, at which point the next item(s) will start shrinking).

like image 139
Sheraff Avatar answered Sep 08 '25 19:09

Sheraff