首页 > 解决方案 > Increment headings and variables using a for loop that apply's font-size in scss

问题描述

I am trying to loop through all 6 headings and apply font-size through a mixin from 6 font-size variables. But I keep getting an undefined variable. It is not recognizing the variable increment. Am I doing something wrong or is this simply not possible? Seems simple enough in my head anyway He is a link to sassmeister Thanks for any help or insight

// Variables

$font-h1: 40px;
$font-h2: 28px;
$font-h3: 24px;
$font-h4: 20px;
$font-h5: 18px;
$font-h6: 14px;

//Mixin

@mixin font-size($size) {
  font-size: $size;  
}

@for $i from 1 through 6 {
  h#{$i} {
    // font-size: #{$i};
    @include font-size( $font-h#{$i} );
  }
}

// Expected out

h1 {
    font-size: 40px
} 
etc...

// Actual Ouput

Undefined variable: "$font-h".

标签: sassscss-mixins

解决方案


I would go with a map as it tends to be more flexible – e.g:

$font-size:(
    h1 : 40px,
    h2 : 28px,
    h3 : 24px,
    h4 : 20px,
    h5 : 18px,
    h6 : 14px
);

@each $header, $size in $font-size {
    #{$header}{ font-size: $size; }
} 




//  Bonus 
//  If you need to apply a font-size to another 
//  element you can get the size using map-get 
.class {
    font-size: map-get($font-size, h3);
}


//  Function and mixin to handle the above
@function font-size($key){
    @return map-get($font-size, $key);
}
@mixin font-size($key){
    font-size: font-size($key); 
}


.class {
    font-size: font-size(h3);  // use it as function
    @include font-size(h3);    // use it as include
}

推荐阅读