How to use flexbox to create a span based on the width of the content
P粉726234648
2023-08-15 12:26:13
<p>I have used span and div in a fixed width flex-row parent element</p>
<p><br /></p>
<pre class="brush:css;toolbar:false;">.parent {
display: flex;
flex-direction: row;
width: 230px;
background-color: blue;
}
.child1 {
background-color: red;
}
.child2 {
min-width: 40px;
}</pre>
<pre class="brush:html;toolbar:false;"><div class="parent">
<span class="child1">This is some text in span</span>
<div class="child2"/>
</div></pre>
<p><br /></p>
<p>I want the span to always be the same width as the text, and the div to take up the entire remaining width of the parent element. Now (as you can see in the code snippet), when the text moves to a new line, the red background area is wider than the text. How to fix this code? I need the red background to end exactly at the edge of the text</p>
Perhaps you could set
parent
to a grid and use fr units for measurements?This will make the text container the same width as the text, and make the remaining containers take up 1 share of the remaining space (no other container will take up 100% of the space).
For row display, just change columns to rows.