Controlling whitespace around flexbox items

Wednesday, Jul 29, 2020
Frontend

Earlier we briefly looked at how flexbox can be used to create multiple column layout. Now we want to go a step further and see how white space around items can be controlled to create a nicer looking layout. When div's display is set to flex, it lines up its children elements along main axis (horizontal). In the example below, both section one and two have a parent div with class “cols”, each section has a common class “col” and has an individual class “col-2” and “col-1” respectively. So the following css produces the layout below (padding/margin code for body, h1 and h2 is not shown for clarity):

.cols {
    display: flex;
}

.col-1 {
    background: #86c4ba;

before

We will do the following to manage the whitespace around both sections:

.cols {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
}

.col {
    padding: 1em;
    margin: 2em;
}

.col-1 {
    width: 25%;
    background: #86c4ba;
}

.col-2 {
    width: 50%;
}

after