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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay