1

I was wondering how to get the spacer variables generic with the use of Bootsrap in a custom class.

I have a class .box and want to apply the class pl-3 of bootstrap 4. I don't want to add the class inline in HTML but want to style it in sass.

I want to use the spacer variables of Bootstap and not hardcoded in the class itself. So if i want to change the padding in the future i only have to change the padding in the sass.

I have the following defined:

$spacer: 1rem !default;    
$spacers: (
      0: 0,
      1: ($spacer * .125),      // 2px
      2: ($spacer * .25),       // 4px
      3: ($spacer * .375),      // 6px
      4: ($spacer * .5),        // 8px
      5: ($spacer * 0.75),      // 12px
      6: ($spacer * 1)          // 16px
    )

What is the best way to do this? What i have found out is this:

.box{
   @extend .pl-3;
}

But i don't like it this way. It's not very self explaining Is there an other/ better way to do this? Like:

.box{
       padding-left: $spacer-3;
    }
amernov
  • 626
  • 1
  • 8
  • 18
  • 1
    First thing its bad approach to override the values of default with the custom one with same variable names Second if i was not wrong you just initialize the value of viable in sass like `$custom-space-5: 5px` and then in `.box` you can use it like `.box{padding:$custom-space-5}`, so when ever you change the value of your variable it changes where ever its used. – Awais Dec 30 '19 at 11:39

2 Answers2

3

Use the SCSS function map-get() as documented here.

.box {
  padding-left: map-get($spacers, 3);
}

Codepen

Arajay
  • 552
  • 6
  • 7
0

You could use a simple function (note Sass lists starts at index 1 why we use $n +1)

@function space($n){ 
  @return nth(0 .125 .25 .375 .5 .75 1, $n + 1) * 1rem;
}


.box{
   padding-left: space(3);  // 0.375rem;
}
Jakob E
  • 4,476
  • 1
  • 18
  • 21