Consider the example below, a tooltip or modal or something outside the normal layout flow where the container is able to grow, but should shrink to fit its contents. Here I would like the header (blue) to fit on a single line, (greedily) expanding the parent. That is, to behave like it normally would. But the "body text" (red) should only grow to fill the available space and then (eagerly) wrap the text.
Unfortunately there seems to be no obvious CSS property to express eagerly wrapping text layout.
article {
position: absolute;
background: whitesmoke;
padding: 1em 2em;
}
header {
color: blue;
}
main {
color: red;
}
<article>
<header>This should expand parent to fit.</header>
<main>This should use available space, but wrap instead of expanding parent.</main>
</article>
PS: This might just be my search or problem description skills being terrible, but I've not found anything even describing this problem, let alone the solution. Please link anything you can find that is related to this.
One trick I stumbled upon is to set min-width: 100%
and then set max-width
to the actual minimum value.
min-width: 100%;
max-width: min-content; /* or even 0 */
You might think that setting max-width: 100%
as well would work. Nope! I'm guessing because 100%
then would refer to the width after its "preferred" width has been applied.
I would love a proper explanation of why this works, but my understanding of it is simply that max-width
overrides the internal "preferred" width, and then min-width
overrides max-width
. Seeing as this is CSS, I'm sure it's much more complicated though :)
article {
position: absolute;
background: whitesmoke;
padding: 1em 2em;
}
header {
color: blue;
}
main {
color: red;
min-width: 100%;
max-width: min-content;
}
<article>
<header>This should expand parent to fit.</header>
<main>This should use available space, but wrap instead of expanding parent.</main>
</article>