As great as Flexbox is when it comes to aligning items on the page, one issue I have always had is that the Flexbox style options need to be repeated quite a few times and don't feel very DRY.
For example, let's look at this container class that is used to style card elements on the Devcamp site:
There is a quite a bit of nearly duplicate code with all of the calls to 'display: flex', 'justify-content', etc. Thankfully, Scss mixins are to the rescue for cleaning up this code. Standard mixins are helpful since they allow you to call shared styles from anywhere in a stylesheet. However, they can also perform more advanced behavior, such as:Using named and default arguments Working with conditionals Setting shared styles that can be dynamic
In the code below I've created a 'flex-config' mixin that completely removes all of the messy flex style rules:
So what exactly is going on? Let's walk through it line by line:I'm setting a full list of variables that could potential be used for this flexbox implementation and I'm setting all of them to false by default. Inside of the mixin I always have the 'display: flex' rule set since that is needed for each time that the mixin is included. Then I check to see if each variable is not false (this means that the variable was used). If so, I set the style rule to the value passed in as the argument. From there I simply include the mixin in each place where the old flexbox code was. For the locations where only the 'display' rule was called I can call the mixin with no arguments. In the locations that had a set of rules, such as align-items or flex-direction, I pass in the values with named arguments.
And that's it. Not only is this container class cleaned up, but not I can call this mixin from anywhere else in the application that uses flexbox.