When Text goes into 2+ Lines

I am always running into this problem.
Lets say i have a button which is display: inline-block (or flex, or inline-flex) and max-width: fit-content; background-color: red; border-radius: 1em; As long as the inner text does not “break” into two+ lines it looks good. The width of the button is defined by its text. But when the text “breaks” in two+ lines the button gets width 100% because the text is 100% width (becomes block-element) . I want it to fit the content. Any ideas what to do? I cannot use max-width for the button because its a cms and i dont know what text will be inside.

I made a codepen:
https://codepen.io/ollio/pen/poMGVWQ

Hi there!
To keep the button width fitting its content even when the text wraps, you could try a few approaches:
Use display: inline-flex;: This typically allows the button to grow only with its content, but if you experience the 100% width issue, try using min-width: 0; and max-width: fit-content;.

Example code
.button {
  display: inline-flex;
  max-width: fit-content;
  min-width: 0; /* Prevents it from growing wider */
  background-color: red;
  border-radius: 1em;
  padding: 0.5em 1em;
  white-space: normal; /* Allows wrapping within the max width */
}

Use inline-grid: inline-grid can help maintain the button’s width more precisely, as it doesn’t automatically expand to 100% width on wrapping.

Example code
.button {
  display: inline-grid;
  max-width: fit-content;
  background-color: red;
  border-radius: 1em;
  padding: 0.5em 1em;
}

Set width: auto; with white-space: pre-wrap;: width: auto; often helps prevent the full-width expansion while pre-wrap keeps the text wrapping naturally.

Example code
.button {
  display: inline-block;
  max-width: fit-content;
  width: auto;
  background-color: red;
  border-radius: 1em;
  padding: 0.5em 1em;
  white-space: pre-wrap;
}

Thanks for your suggestions, but neither of them work.
I discussed this issue on discord. There really is no css solution for this problem. I need to use JS.

if you know button text in advance (static) then i suppose you can always make use of “markups and styles” to meet your needs, right?