【问题标题】:SASS Function Reduce Line Height as Font Size IncreasesSASS 函数随着字体大小的增加而减小行高
【发布时间】:2021-05-30 12:33:07
【问题描述】:

许多人在构建网站时可能已经注意到,较大的字体通常需要较小的行高。我目前在我的 SASS 项目中有一个标题的字体大小列表,我正在寻找一个可以根据给定高度自动计算吸引人的行高的函数。我目前正在做以下事情:

$font-size--h1: 4rem;
$font-size--h2: 3rem;
$font-size--h3: 2rem;
$font-size--h4: 1.5rem;
$font-size--h5: 1.25rem;
$font-size--h6: 1.1rem;

$font-sizes: (
    h1: $font-size--h1,
    h2: $font-size--h2,
    h3: $font-size--h3,
    h4: $font-size--h4,
    h5: $font-size--h5,
    h6: $font-size--h6
);

@each $heading, $font-size in $font-sizes {

    #{$heading} {
        font-size: $font-size;
    }
}

我想要的是一个可以接受字体大小然后输出适当行高的函数,所以我的@each 循环看起来像这样:

@each $heading, $font-size in $font-sizes {

    #{$heading} {
        font-size: $font-size;
        line-height: calculate-line-height($font-size); // Some function
    }
}

以前有人做过这样的功能吗?我发现 an article 对此进行了描述,但无法将所描述的函数转换为有效的 SASS 函数。

【问题讨论】:

    标签: css function sass


    【解决方案1】:

    这是您链接的文章中两个函数的 SCSS 端口:

    @use "sass:math";
    
    @function getFontSize($base, $ratio, $size) {
      @return $base * math.pow($ratio, $size);
    }
    
    @function getLineHeight($base, $ratio, $size, $gridSize) {
      $lineHeight: math.round($base * math.pow($ratio, $size));
      @return if($lineHeight % $gridSize == 0, $lineHeight, $lineHeight + $lineHeight % $gridSize);
    }
    

    (请注意,由于您使用的是rem 而不是ptpx,因此我省略了第一个函数中的舍入。)

    不过,要使用该系统,您需要用相同的术语重述字体大小系列:基本字体大小、基线高度、大小之间的比率以及所有大小共享的网格大小,然后六种尺寸本身。这可能看起来像这样(尽管您需要调整数字):

    $sizes: 1, 2, 3, 4, 5, 6;
    @each $size in $sizes {
        h#{$size} {
            font-size: getFontSize(1rem, 1.1, 7 - $size);
            line-height: getLineHeight(18px, 1.1, 7 - $size, 18px);
        }
    }
    

    Here's a pen showing the entire thing.

    【讨论】:

      猜你喜欢
      • 2014-03-01
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 2021-04-12
      • 2012-09-12
      • 1970-01-01
      相关资源
      最近更新 更多