Kcko
10/9/2019 - 6:27 PM

Recursive SCSS mixins and functions

// 1)

@mixin test($val) {
  width: $val;
  height: $val;
  @if $val > 0 {
    @include test($val - 1);
  }
}

.x
{
  @include test(5);
}

/*

.x {
  width: 5;
  height: 5;
  width: 4;
  height: 4;
  width: 3;
  height: 3;
  width: 2;
  height: 2;
  width: 1;
  height: 1;
  width: 0;
  height: 0;
}

*/


// 2)
// @example: https://codepen.io/_lacus/pen/xwZvvx

@mixin opacityStair($fade: 0.9, $step: 0.1) {
	// Recursive sass example
    
	& + * {
		opacity: $fade;
		@if $fade <= $step {
		    // exit
		} @else {
			@include opacityStair($fade - $step, $step)
		}
	}
}

div {
	@include opacityStair();
}


div div {
  width: 100%;
  height: 33px;
  background-color: green;
}

/*
  
  div + * {
  opacity: 0.9;
}

div + * + * {
  opacity: 0.8;
}

div + * + * + * {
  opacity: 0.7;
}

div + * + * + * + * {
  opacity: 0.6;
}

div + * + * + * + * + * {
  opacity: 0.5;
}

div + * + * + * + * + * + * {
  opacity: 0.4;
}

div + * + * + * + * + * + * + * {
  opacity: 0.3;
}

div + * + * + * + * + * + * + * + * {
  opacity: 0.2;
}

div + * + * + * + * + * + * + * + * + * {
  opacity: 0.1;
}

div div {
  width: 100%;
  height: 33px;
  background-color: green;
}

  
*/


// 3) 
// @link: https://codepen.io/mirisuzanne/pen/bBdEXm

// define your colors
$colors: (
  'pink': #E2127A,
  'brand-primary': 'pink',
  'site-background': 'brand-primary',
);

// color function
@function color($color) {
  // our conditional statement
  @if map-get($colors, $color) {
    // follow the path one step
    $new-color: map-get($colors, $color);

    // recursion!
    $color: color($new-color);
  }
  
  @return $color;
}

// use your new function!
body {
  background: color('x');
}

// other styles...
body {  
  font-size: 8vmin;
  font-family: monospace;
  text-align: center;
  padding: 40vmin 2em;

  &::after {
    content: "‘site-background’ == #{color('site-background')}";
  }
}

/*


@charset "UTF-8";
body {
  background: "x";
}

body {
  font-size: 8vmin;
  font-family: monospace;
  text-align: center;
  padding: 40vmin 2em;
}

body::after {
  content: "‘site-background’ == #E2127A";
}
*/