Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Flexbox with padding in the inner items

Tags:

html

css

flexbox

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>
like image 951
azrael Avatar asked Jan 09 '18 15:01

azrael


2 Answers

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>
like image 81
Michael Benjamin Avatar answered Oct 23 '22 10:10

Michael Benjamin


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>
like image 20
Temani Afif Avatar answered Oct 23 '22 10:10

Temani Afif