Home > Back-end >  flex-shrink only the widest parts to some percentage, then shrink equally
flex-shrink only the widest parts to some percentage, then shrink equally

Time:09-27

Imagine there's some breadcrumb bar - a line with various count of links, each link has ellipsis, and it should shrink if overflow.

Overflow should be smart - if there're 5 links, and 2 links are much wider than others, they have to be shrinked to 20%, and 3 short links should stay as they are.

If one link is much wider, and the rest 4 links are short, and they fit, then no shrink should happen. The widest link should not shink to 20% if the overall width is enough.

I'm trying different approaches but could not find one that fits these (natural) requirements. Is it possible to achieve without JavaScript?

I tried various combinations of flex-basis & min/max width, but no success yet:

enter image description here

CodePudding user response:

It would be easier if you can add a class dynamically according to the length of the text content.

In that case, only give flex-shrink to those are too wide:

.breadcrumbs {
  width: 300px;
  display: flex;
  align-items: center;
  border: 1px solid #000;
  margin: 0 0 50px 0;
  padding: 5px;
}

.breadcrumb-separator {
  flex: 0 0 auto;
  margin: 0 5px;
}

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

.breadcrumb {
  flex: 0 0 auto;
}

.breadcrumb.long {
  flex-shrink: 1;
}
<div class="breadcrumbs">
  <a href="#" class="breadcrumb ellipsis long">
    SomeLongTitleGoesHereAndItsTooWideToFit
  </a>
  <div class="breadcrumb-separator">&raquo;</div>
  <a href="#" class="breadcrumb ellipsis">
    Short
  </a>
  <div class="breadcrumb-separator">&raquo;</div>
  <a href="#" class="breadcrumb ellipsis">
    Short
  </a>
  <div class="breadcrumb-separator">&raquo;</div>
  <a href="#" class="breadcrumb ellipsis">
    Short
  </a>
</div>

CodePudding user response:

Try this example with additional max-width: min-content; in the .breadcrumb class and some flex property changes. Without extra classes.

.breadcrumb-separator {
  flex: 1 0 auto; /* changed */
  margin: 0 5px;
}

.breadcrumb {
  max-width: min-content; /* new line */
  flex: 0 1 100%; /* changed */
}

  • Related