5

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>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
azrael
  • 263
  • 3
  • 13

2 Answers2

6

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>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
1

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>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415