cssflexbox

shrink one element first before shrinking the second in flexbox


I have a flex container with two elements, I'm trying to shrink the first element to its min-width before shrinking the second. The caveat is that I want the first element to not grow beyond its content size.

EDIT: thanks to the answer below, here is a working solution, without unnecessary rules:

.p {
  display: flex
}

.label {
  flex-basis: 50px; // How far it will shrink
  flex-grow: 1;
  max-width: max-content; // Limit how much it will grow
}
<div class="p">
  <div class="label">
    My long label that should shrink first with an ellipsis
  </div>
  <div class="values">
    My values which I do not want to shrink before the label
    shrunk to its min-width, and that should be next to the label
    without a big gap between the two
  </div>
</div>

It does make label shrink first, but the problem is that it makes it grow as much as possible if there is space, creating a big gap between label and values.


Solution

  • consider max-width on the label to avoid the grow part

    .p {
      display: flex
    }
    .label {
      flex-basis: 50px;
      flex-grow: 1;
      max-width: max-content;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    <div class="p">
      <div class="label">
        My long label that should shrink first with an ellipsis
      </div>
      <div class="values">
        My values which I do not want to shrink before the label
        shrunk to its min-width
      </div>
    <div>