DEV Community

Tanmay Naik
Tanmay Naik

Posted on • Edited on

4

Implementing Flexbox with SCSS mixins

CSS and HTML

I was scouring the internet for a good mixin for flexbox but I would always come across mixins like these,

@mixin flexbox() {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
}
Enter fullscreen mode Exit fullscreen mode

with a mixin for every possible property,

@mixin justify-content($justify) {
  -webkit-justify-content: $justify;
     -moz-justify-content: $justify;
      -ms-justify-content: $justify;
          justify-content: $justify;
            -ms-flex-pack: $justify;
}
Enter fullscreen mode Exit fullscreen mode

While this may work for a lot of people, I still felt that it could be made simpler, or "DRY'er". I'm pretty sure someone must have done something like this before, but I couldn't find it. So after a little bit of struggling around with SCSS mixins and functions, I came up with this,

//Get the value for justify-content
@function getJustify($arg){
$justify: (
'sa':space-around,
'sb':space-between,
'se':space-evenly,
'c':center,
'fs':flex-start,
'fe':flex-end
);
@each $key,$value in $justify{
@if($key == $arg){
@return $value;
}
}
}
//Get the value for align-items
@function checkAlign($arg){
$align: (
'b':baseline,
's':stretch,
'c':center,
'fs':flex-start,
'fe':flex-end
);
@each $key,$value in $align{
@if($key == $arg){
@return $value;
}
}
}
//Display flex
@mixin d-flex(){
display: flex;
@content
}
//Applied example
div{
@include d-flex{
justify-content: getJustify(c);
align-content: getAlign(c);
}
}

More functions can be created and extended into the mixin such as flex-direction, flex-wrap, flex-grow, etc. with the @content directive in a similar way. It can also be used on properties that use the same values like justify-self or align-self. I will be updating this post with a github repo for all the functions and mixins soon.


Would love to know if anyone finds it useful. Thanks.

Top comments (0)