How can I maintain width ratio defined by flex-grow
between two items when one of which is partially filled with padding? It does not work. Ratio depends on the container width.
<div style="display: flex;">
<div style="flex-grow: 3; padding: 4rem; background-color: red;">
</div>
<div style="flex-grow: 2; background-color: green;">
</div>
</div>
The flex-grow
property is not designed for precision sizing of flex items. It's job is to distribute space in the container among flex items. So flex-grow
is not the best tool for this job.
Instead, use flex-basis
, which is the equivalent of width
or height
(depending on flex-direction
) in a flex container.
Then add box-sizing: border-box
to integrate the padding into the flex item's width.
revised fiddle demo
<div style="display: flex;">
<div style="flex-basis: 60%; padding: 4rem ; background-color: red; box-sizing: border-box;">
</div>
<div style="flex-basis: 40%; background-color: green;">
</div>
</div>
use width
(or flex-basis
) instead of flex-grow
:
* {
box-sizing: border-box; /* Don't forgert this to include padding/border inside width calculation */
}
<div style="display: flex;height:20px;margin-bottom:10px;">
<div style="flex-grow: 3; background-color: red;">
</div>
<div style="flex-grow: 2; background-color: green;">
</div>
</div>
replace by width
<div style="display: flex;height:20px;margin-bottom:10px;">
<div style="width:calc((3 / 5) * 100%); background-color: red;">
</div>
<div style="width:calc((2 / 5) * 100%); background-color: green;">
</div>
</div>
then add padding
<div style="display: flex;margin-bottom:10px;">
<div style="width:calc((3 / 5) * 100%); padding:3rem; background-color: red;">
</div>
<div style="width:calc((2 / 5) * 100%); background-color: green;">
</div>
</div>
same result with flex-basis
<div style="display: flex;margin-bottom:10px;">
<div style="flex-basis:calc((3 / 5) * 100%); padding:3rem; background-color: red;">
</div>
<div style="flex-basis:calc((2 / 5) * 100%); background-color: green;">
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With