Reputation: 263
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>
Upvotes: 5
Views: 10005
Reputation: 21
I usually doing padding style in the inner tag of the inner items:
<div style="display: flex;">
<div style="flex-grow: 3; background-color: red;">
<div style="padding: 4rem;">Some content</div>
</div>
<div style="flex-grow: 2; background-color: green;">
Some content
</div>
</div>
Upvotes: 0
Reputation: 273571
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>
Upvotes: 1
Reputation: 371699
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.
<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>
Upvotes: 7