0

If you run the code snippet below you can see that the width used for the top <div> is 200px (max-width). But in reality it doesn't need to use the max-width because the last <p> is wrapped. Instead, the wanted result is to use the width that the bottom <div> uses (~140px).

How can I use the preferred width and still get the item to wrap?

div {
  max-width: 200px;
  width: fit-content;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  background-color: green;
  margin-bottom: 8px;
}

p {
  background-color: red;
}
<div>
  <p>
    test
  </p>
  <p>
    this is a long text
  </p>
  <p>
    short text
  </p>
</div>

<div>
  <p>
    test
  </p>
  <p>
    longer text
  </p>
</div>
Mees
  • 75
  • 1
  • 10

1 Answers1

-1

If my understanding of the question is correct, you can achieve this by using the flex-basis on the p elements instead of max-width on the div :

div {
  min-width: 140px;
  width: fit-content;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  background-color: green;
  margin-bottom: 8px;
}

p {
  flex-basis: auto;
  background-color: red;
}
Johan
  • 2,088
  • 2
  • 9
  • 37