I have an outer div with a fixed width, and an inner div. Inside the inner div can be a button with a fixed size or a div with width 100%.
Is there a way to have the inner div fit the button at its width, and fit the full width div at full width?
I tried various combinations of width, minWidth, maxWidth, some flex properties, but nothing seems to work.
<div style="width:500px">
<div style="??">
<button>Button</Button>
</div>
</div>
and
<div style="width:500px">
<div style="??">
<div style="width:100%/>
</div>
</div>
2
Answers
Hmm you can achieve this layout using flexbox and a combination of min-width and max-width properties. Here’s how you can do it:
Let me explain what’s happening here:
For the button case:
min-width: 0;
on the button ensures that it can shrink beyond itsintrinsic width to fit the container.
lex-grow: 1;
makes the button occupy the remaining space within theflex container.
For the div case:
We use
display: flex;
on the inner div again.Inside, the child div with width: 100%; will naturally expand to fill
the available space, as it’s the only item in the flex container.
This should give you the desired behavior where the button fits its width and the div expands to fill the available space.
All you need is
fit-content
on that inner div: