code

계산 결과에 단위 유형 추가

codestyles 2020. 12. 29. 07:06
반응형

계산 결과에 단위 유형 추가


최근에 CSS를 SASS 스타일 시트로 리팩터링했습니다. 저는 SCSS를 저장할 때마다 CSS를 다시 생성하는 VS2012 용 Mindscape Web Workbench 확장사용하고 있습니다. 다음과 유사한 코드로 시작했습니다.

/* Starting point: */
h1 { font-size: 1.5em; /* 24px ÷ 16px */ }

그런 다음 먼저 이것을 리팩토링하려고 시도했습니다.

/* Recfator: */
h1 { font-size: (24px / 16px)em; }

그러나 이것은 불행히도 다음을 생성합니다.

/* Result: */
h1 { font-size: 1.5 em; }              /* doesn't work, gives "1.5 em" */

내가 원하지 않는 여분의 공간을 주목하십시오 . 몇 가지 대안을 시도해 보았습니다. 여기에 몇 가지가 있습니다.

h1 { font-size: (24/16)em; }           /* doesn't work, gives "1.5 em" */
h2 { font-size: 24 / 16em; }           /* doesn't work, gives "24/16em" */
h3 { font-size: (24px / 16px) * 1em; } /* works but "* 1 em" feels unnecessary */
h4 { font-size: (24em) / 16; }         /* works, but without "px" it's not 
                                          really conveying what I mean to say */

나는 또한 변수로 이러한 변형을 시도했지만 (어쨌든 그것들을 원하기 때문에) 상황을 많이 바꾸지 않았습니다. 이 질문의 예를 매끄럽게 유지하기 위해 변수를 생략했습니다. 그러나 변수 사용에 의존하는 솔루션을 기꺼이 받아 들일 것입니다 (깨끗한 방식으로).

나는 '/'에 대한 관련 SASS 문서 를 살펴 보았고 , '/'문자가 이미 기본 CSS에서 의미를 가지고 있기 때문에 이것이 SASS에 대해 어려운 문서라는 점에 감사드립니다. 어느 쪽이든 깨끗한 해결책을 원했습니다. 여기에 뭔가 빠졌나요?

추신. 이 블로그 게시물 은 사용자 정의 함수를 사용하여 하나의 솔루션을 제공합니다. 그래도 약간 무거워 보이므로 위의 시도와 일치하는 "더 깨끗한"솔루션이 있는지 궁금합니다. 누군가 "함수 접근 방식"이 더 나은 (또는 유일한) 해결책이라고 설명 할 수 있다면 저도 대답으로 받아 들일 것입니다.

추신. 이 관련 질문 은 특히 ​​추가 계산을 원하지만 거의 같은 것 같습니다. 받아 들인 대답 은 세 번째 해결 방법 (곱하기 1em)이지만 추가 계산을 수행하는 기능을 포기할 의향이 있다면 다른 (더 깨끗한) 방법이 있는지 알고 싶습니다. 이 질문에서 언급 한 방법 ( "보간")이 유용할까요?


결론 : SASS의 계산 결과에 단위 유형 (예 em:)을 어떻게 깔끔하게 추가 할 수 있습니까?


숫자에 단위를 추가하는 유일한 방법은 산술을 이용하는 것 입니다.

연결 등의 작업을 수행 할 수 있도록 (예. 1 + px) 또는 보간 (예. #{1}px) 만 생성합니다 문자열을외모 수있다. 다른 산술 연산에서 절대 값을 사용하지 않을 것이라고 100 % 확신하더라도이 작업을 수행해서는 안됩니다 .

산술 연산을 수행 할 수없는 것보다 더 중요한 것은 숫자를 예상하는 다른 함수와 함께 사용할 수 없다는 것입니다.

$foo: 1; // a number
$foo-percent: $foo + '%'; // a string

.bar {
    color: darken(blue, $foo-percent); //Error: "1%" is not a number!
}

$ amount : "1 %"는 '어둡게'의 숫자가 아닙니다.

숫자를 문자열로 캐스팅하여 얻을 수있는 것은 없습니다. 단위를 추가하려면 항상 산술 (1 곱하기 또는 0 더하기)을 사용합니다.

$foo: 1; // a number
$foo-percent: $foo * 1%; // still a number! //or: $foo + 0%

.bar {
    color: darken(blue, $foo-percent); //works!
}

산출:

.bar {
  color: #0000fa;
}

다음은 Flexbox mixin 라이브러리의 일부로 작성한 mixin입니다. 문자열을 전달하면 질식 할 것입니다 (Flexbox에 익숙하지 않은 사용자를 위해 원래 사양은 box-flex속성에 대한 정수만 허용 합니다. flex: auto또는 flex: 30em유사한 box-flex속성 과 호환되도록 만들 수 없습니다 . 믹스 인은 노력하지 않습니다)

@mixin flex($value: 0 1 auto, $wrap: $flex-wrap-required, $legacy: $flex-legacy-enabled) {
    @if $legacy and unitless(nth($value, 1)) {
        @include legacy-flex(nth($value, 1));
    }

    @include experimental(flex, $value, flex-support-common()...);
}

@mixin legacy-flex($value: 0) {
    @include experimental(box-flex, $value, $box-support...);
}

다음 중 하나를 시도 할 수 있습니다.

font-size: $size * 1px;

또는

font-size: $size + unquote("px");

$size계산 결과는 어디 입니까?


선호하는 방법을 선택하세요

$font: 24px;
$base: 16px;

변수 없음

.item1 { font-size: #{(24px / 16px)}em; }

변수 만 사용

.item2 { font-size: #{$font / $base}em; }

하나의 변수

.item3 { font-size: #{$font / 16px}em; }
.item4 { font-size: #{24px / $base}em; }

그들 모두에 대한 출력

.item1 { font-size: 1.5em; }
.item2 { font-size: 1.5em; }
.item3 { font-size: 1.5em; }
.item4 { font-size: 1.5em; }

사용 된 방법을 보간 # {} 이라고합니다.


나는 당신이 이것을 묻는 이유는 주변 컨텍스트에서 1 em = 16 px 이고이 관계를 사용하여 대상 글꼴 크기를 픽셀에서 em으로 변환하기를 원하기 때문이라고 가정합니다.

If so, the right thing to do is to multiply the font size with the scaling factor 1em / 16px, like this:

$h1-font-size: 24px;
$body-font-size: 16px;

$body-em-scale: 1em / $body-font-size;

h1 {
  font-size: $h1-font-size * $body-em-scale;  // -> 1.5em
}

or just:

h1 {
  font-size: $h1-font-size * (1em / $body-font-size);  // -> 1.5em
}

This is exactly how it works in physics, too: if have, say, 50 moles of water, and you want to know how much that weighs in grams, you multiply the amount of water you have (= 50 mol) with the molar mass of water (≈ 18 g/mol) to find out that your sample of water weighs 50 mol × 18 g/mol ≈ 900 grams. Converting pixels to ems in SASS works just the same way: first find out how many ems there are per pixel, in the context you intend to use the rule in, and then multiply the size in px with that ratio, expressed in units of em/px.


Ps. Of course, if the units you were converting between had a fixed ratio that SASS already knew about, then you could simply let it do the conversion automatically for you, using the "zero plus trick". For example, if you wanted to convert the font size from px to cm, you could simply do:

h1 {
  font-size: 0cm + $h1-font-size;  // -> 0.635cm
}

This works because SASS allows you to add together two values given in compatible units (like px and cm), and will express the result in the same units as the first value in the sum. The reason this trick doesn't work for px -> em is that here the conversion factor is not fixed, but depends on the surrounding context, and so SASS doesn't know how to do the conversion automatically.


The best way to add a unit, is to use ... * 1em or ... + 0em where em is the unit you want to get:

font-size: (24px/16px) + 0em; // ... + 0px for px
//or
font-size: (24px/16px) * 1em; 
//both produce: font-size: 1.5em;

This way, it will remain as a number so you can use it in math operations or other functions.

But if you want the result as a string or don't care the numeric value of result for some reason, you can also simply get it this way:

font-size: (24px/16px) + em; //font-size: 1.5em; //em does not include quotations

no need to use unquote or #{} here (as written in other answers)!

ReferenceURL : https://stackoverflow.com/questions/13905407/append-unit-type-to-the-result-of-a-calculation

반응형