Flexbox is a very powerful CSS specification for layout. Though it is sometimes used for large scale page layouts, flexbox is most suited to smaller scale layouts, such as individual components. If you're using flexbox in this way, you may find yourself writing the same rules over and over. We're going to look at a few basic helper classes that can make adding flexbox to your components a bit quicker. These classes don't provide every possible flexbox rule, rather just the basic ones that I find I use most often. I find that classes like these are often useful for small things, like matching the heights of a row of elements, and vertically centering their contents.
I'm using SCSS here for brevity, but you could easily write the same classes in regular CSS.
.flex-parent { // Add this class to create a flexbox parent
display:flex;
&.flex-direction-column { // This changes the layout direction from the default horizontal to vertical
flex-direction:column;
}
&.justify-content-center { // This centers the parent's children along the main axis (horizontal by default, vertical if the parent has the flex-direction-column class)
justify-content:center;
}
&.align-items-center { // This centers the parent's children along the cross axis
justify-content:center;
}
&.flex-wrap-wrap { // This allows the children to wrap as needed
flex-wrap:wrap;
}
@for $i from 1 through 12 { // Here we loop through numbers 1 to 12, generating flex child classes for each number, eg. .flex-1, .flex-2 etc.
.flex-#{$i} {
flex:$i;
}
}
}
Here is an example of a component layout using our flexbox helper classes:
<div class="flex-parent">
<div class="flex-1 flex-parent flex-direction-column justify-content-center">1</div>
<div class="flex-2 flex-parent flex-direction-column justify-content-center">2</div>
<div class="flex-3 flex-parent flex-direction-column justify-content-center">3</div>
<div class="flex-4 flex-parent align-items-center">
<div class="flex-parent flex-direction-column">
<div class="flex-1">row 1</div>
<div class="flex-1">row 2</div>
<div class="flex-1">row 3</div>
</div>
</div>
</div>
For information on vendor prefixes for flexbox, click here, but I highly reccommend using a tool like Autoprefixer so you don't need to worry about them.
Top comments (0)