问题
I have a fixed-position container element with two children. Both children contain text. I want one of the children to dynamically set the width of the container with its content. I want the other child's text to wrap appropriate based on that width.
For example:
.container {
position: fixed;
}
.wrap {
background: red;
}
.stretch {
background: green;
}
<div class="container">
<div class="wrap">
this text is very very long
</div>
<div class="stretch">
shorter text
<div>
</div>
In this example, I would like the container's width to match the shorter green .stretch
div
. I want the red .wrap
div
to have the same width, with the text wrapped inside, like:
回答1:
The solution's come up with me was:
- The child
div
needs to stretch its width depends on its content ->max-content
- The parents's width needs to be as shrink as possible depends on its content ->
min-content
The solution code with variant bahaviors:
.container {
width: min-content;
border: 2px solid blue;
margin: 5px;
}
.wrap {
background: red;
width: auto; /* default btw */
}
.stretch {
background: green;
width: max-content;
}
<div class="container">
<div class="wrap">
this text is very very long
</div>
<div class="stretch">
shorter text
</div>
</div>
<div class="container">
<div class="wrap">
shorter
</div>
<div class="stretch">
shorter text
</div>
</div>
<div class="container">
<span class="wrap">
shorter
</span>
<div class="stretch">
shorter text
</div>
</div>
You can read more about min-content and max-content from this answer or the specification.
max-content
inline size: the narrowest inline size it could take while fitting around its contents if none of the soft wrap opportunities within the box were taken.
min-content
inline size: the narrowest inline size a box could take that doesn’t lead to inline-dimension overflow that could be avoided by choosing a larger inline size. Roughly, the inline size that would fit around its contents if all soft wrap opportunities within the box were taken.
来源:https://stackoverflow.com/questions/59552629/prevent-child-from-from-stretching-parent-container