When using flexbox approach to page layout the flex-basis
property can be applied to flex items in order to control the amount of space the item will ‘flex’ into (in other words its width).
Consider a common design request. The designer would like a 3 column design as follows:
The basic HTML would be:
<div class="container"> <div class="colOne">... Some content</div> <div class="colTwo">... Some content</div> <div class="colThree">... Some content</div> </div>
The CSS rules to set up a flex layout would be:
.container{ display: flex; width: 1200px; }
By default all three columns will ‘flex’ to fit evenly. Given the container is 1200px wide each of the three columns therefore takes up 400px.
if we want the central column to be 600px wide and the side columns 300px each we add rules for them as follows:
.colOne, .colThree{ flex-basis:300px; } .colTwo{ flex-basis:600px; }
flex-basis vs width
When flex-basis
is applied to a flex item it will overrule any width
property applied to that item. Take the following CSS rule.
.colTwo{ width: 850px; flex-basis: 600px; }
The width
of 850px will be overruled by the flex-basis
of 650px.
Adding Padding – Remember the Box Model
Our last codePen worked but the text was a little too close together. The obvious solution is to add some padding to ‘colOne’ and ‘colThree’ ie:
.colOne, .colThree{ flex-basis:300px; padding: 10px; }
The box model now becomes interesting. Both ‘colOne’ and ‘colThree’ with a padding of 10px add 40px (left and right 10px padding times 2) to the overall width needed. As a result flex box will by default shrink the flex items so that they still fit inside the 1200px flex container. In this example the true width of ‘colOne’ and ‘colThree’ is now 290px and the ‘colTwo’ 580px – as the 40px padding has to be accommodated.
This might only be of interest if you are after a pixel perfect layout but is something you should be aware off especially when adding images into the design.
Percentages and flex-basis
If you wish to use percentage values for flex-basis
the same box model mathematics will apply. It is recommended that the flex items values flex-basis
add to 100%. Here is a demo using this technique with side columns of 20% and a central column of 60%.
* Note on Extra Properties
Although flex-basis
overrules width
the CSS properties of max-width
and min-width
can be used to limit the upper and lower values respectively.