首页 > 解决方案 > Scss 函数不返回计算值

问题描述

我正在研究用于断点的 mixin,并且遇到以下问题。当设置了特定状态(最大宽度的模式)时,应通过提取一个 em 值(1px/16(默认字体大小))重新计算断点。

这是我的代码的重要部分(我可能会摆脱这个函数,基本上这可以内联完成):


$mediaBreakpoint: map-get( $breakpoints, $breakpoint );

// if the mode is for max-width then subtract 1px.
@if map-get( $modes, $mode ) == 'max-width' {
    $mediaBreakpoint: calculateMaxWidth(#{$mediaBreakpoint})
}
@debug $mediaBreakpoint; 

/**
* calculate the max width based on input
*/
@function calculateMaxWidth($breakpoint){
    $newBreakpoint: calc( #{$breakpoint} - 0.0625em ); // 1px  in em sizing.
    @return $newBreakpoint;
}

但无论我尝试什么,@debug 值都显示为:48em-0.0625em // 这是无效的,我需要实际结果(在本例中为 47.9375)。64em // 有效的最小宽度

这是编译好的css:

@media screen and (max-width: calc( 48em - 0.0625 )) {

}

我错过了什么?

标签: sassscss-mixins

解决方案


I found the answer myself after a lot of debugging. At first I misunderstood the interpolation. After reading the docs in depth I noticed that I should have wrapped the whole calculation instead of just the variable because I am working inside the map expression.

Quoted from the official Sass docs:

Interpolation can be used almost anywhere in a Sass stylesheet to embed the result of a SassScript expression into a chunk of CSS.

I changed my function to calculate like this and then the mixin started working. hooray!

$newBreakpoint: #{$breakpoint - 0.0625em};

推荐阅读