SCSS Error: This operation can't be used in a calculation.

jellykelly·2023년 11월 27일

Resolve errors

목록 보기
1/3

SCSS Interpolation (보간법)

자바스크립트에서는 백틱을 사용한 템플릿 리터럴을 이용하여 문자열 안에 변수나 표현식을 사용할 수 있습니다.

const userName = jellykelly;
const welcomeMsg = `hello ${userName}'s world!`; 

console.log(welcomeMsg) // hello jellykelly's world!


scss에서도 보간법을 사용하여 클래스명이나 속성값에 변수를 사용할 수 있습니다. scss에서는 백틱의 사용 없이 단순히 변수를 `#{}`로 감싸기만 하면 됩니다 🙌
$path-image: '../images';

.object{
    background-image: url('#{$path-image}/image.png');
}

저는 backgroud-image 속성에서 보간법을 가장 자주 사용하는데요.
이미지의 경로를 변수에 저장해두면 경로가 바뀌더라도 일괄 변경이 가능하기 때문이에요.

또, 넓이를 지정하는 공통 클래스를 만들때도 보간법을 활용합니다.
CSS에서는 일일히 반복해서 클래스를 작성해야 하지만, SCSS에서는 @for 반복문을 사용할 수 있기 때문에 간단하게 작성 가능합니다 🙂

$iconWidth: 40px;
$arrowSpace: 24px;
$arrowWidth: calc($iconWidth + ($arrowSpace * 2));


@for $i from 2 through 10 {
  $width: 5 * $i;

  .col-#{$width}p {
    width: calc(#{$width}% - #{$arrowWidth * 0.5});
  }
}

5의 배수로 증가하는 $width라는 변수를 클래스명과 width 속성의 속성값으로 사용했습니다.
보간법을 사용한 본래 의도대로 컴파일링 되었다면 아래와 같은 CSS 코드가 생성됩니다.

.col-10p {
    width: calc(10% - 44px);
}

.col-15p {
    width: calc(15% - 44px);
}

.col-20p {
    width: calc(20% - 44px);
}

...

🚨 Error: This operation can't be used in a calculation.

그런데 갑자기 컴파일되지 않고 에러가 출력됩니다 😨

Error

Compilation Error
Error: This operation can't be used in a calculation.
╷
│width: calc(#{$width}% - #{$arrowWidth * 0.5});
│                     ^

% 연산자를 왜 계산식에서 쓸 수 없는지..?
calc(10% - 44px)와 같이 단위가 다른 값을 calc() 안에서 width의 속성값으로 적용할 수 있는데 왜 에러가 출력될까요? 😭

Documentation says..

⚠️ Heads up!
It’s almost always a bad idea to use interpolation with numbers. Interpolation returns unquoted strings that can’t be used for any further math, and it avoids Sass’s built-in safeguards to ensure that units are used correctly.

Sass has powerful unit arithmetic that you can use instead. For example, instead of writing #{$width}px, write $width * 1px—or better yet, declare the $width variable in terms of px to begin with. That way if $width already has units, you’ll get a nice error message instead of compiling bogus CSS.

출처 : https://sass-lang.com/documentation/interpolation


공식 문서에서는 #{$width}%와 같이 숫자와 함께 보간법을 사용하는 것을 지양하고, 대신 $width * 1%로 바꿔서 사용하기를 권장합니다.

😎 에러 해결

@for $i from 2 through 10 {
  $width: 5 * $i;

  .col-#{$width}p {
    $changeToPercentage: $width * 1%;
    
    width: calc($changeToPercentage - ($arrowWidth * 0.5));
  }
}

$changeToPercentage 라는 변수를 추가하여 $width의 정수 값을 %로 변환하여 삽입 해주는 방식으로 해결!

profile
Hawaiian pizza with extra pineapples please! 🥤

1개의 댓글

comment-user-thumbnail
2023년 11월 29일

👍👍👍

답글 달기