CSS 将单位类型附加到计算结果中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13905407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append unit type to the result of a calculation
提问by Jeroen
I've been refactoring my CSS to a SASS style sheet recently. I'm using the Mindscape Web Workbench extensionfor VS2012, which re-generates the CSS each time you save your SCSS. I started with code similar to this:
我最近一直在将我的 CSS 重构为 SASS 样式表。我正在使用VS2012的Mindscape Web Workbench 扩展,它会在您每次保存 SCSS 时重新生成 CSS。我从类似这样的代码开始:
/* Starting point: */
h1 { font-size: 1.5em; /* 24px ÷ 16px */ }
Then I tried to refactor it first to this:
然后我尝试首先将其重构为:
/* Recfator: */
h1 { font-size: (24px / 16px)em; }
But this unfortunately produces:
但不幸的是,这会产生:
/* Result: */
h1 { font-size: 1.5 em; } /* doesn't work, gives "1.5 em" */
Notice the extra space, which I don't want there. I've tried several alternatives, here are a few:
请注意我不想要的额外空间。我尝试了几种替代方案,这里有一些:
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 */
I've also tried these variants with variables (because I want those anyways), but that didn't change the situation much. To keep the examples in this question sleek I've left out variables. However, I'd happily accept a solution that relies on using variables (in a clean way).
我也尝试过这些带有变量的变体(因为我想要那些),但这并没有太大改变情况。为了使这个问题中的示例保持流畅,我省略了变量。但是,我很乐意接受依赖于使用变量的解决方案(以干净的方式)。
I've gone through the relevant SASS documenation on '/', and appreciate that this is a tough one for SASS because the '/' character already has a meaning in basic CSS. Either way, I was hoping for a clean solution. Am I missing something here?
我已经阅读了有关 '/'的相关 SASS 文档,并意识到这对 SASS 来说是一个艰难的文档,因为 '/' 字符在基本 CSS 中已经具有意义。无论哪种方式,我都希望有一个干净的解决方案。我在这里错过了什么吗?
PS. This blogpostdoes offer one solution, using a user defined function. That seems a bit heavy-weight though, so I'm interested if there's "cleaner" solutions in line with my attempts above. If someone can explain the "function approach" is the better (or even only) solution then I'll accept that as an answer too.
附注。这篇博文确实提供了一种使用用户定义函数的解决方案。不过,这似乎有点沉重,所以我很感兴趣,如果有与我上面的尝试相符的“更清洁”的解决方案。如果有人可以解释“函数方法”是更好(甚至唯一)的解决方案,那么我也会接受它作为答案。
PS. This related questionseems to be about the same thing, though that one specically wants to do further calculations. The accepted answer thereis my third workaround (multiplying by 1em
), but I'd love to know if there's a different (cleaner) way if I'm willing to forego the ability to do further calculations. Perhaps the method mentioned in said question ("interpolation") is useful for me?
附注。这个相关的问题似乎是同一件事,尽管有人特别想做进一步的计算。接受的答案是我的第三种解决方法(乘以1em
),但如果我愿意放弃进行进一步计算的能力,我很想知道是否有不同的(更干净的)方式。也许上述问题(“插值”)中提到的方法对我有用?
Bottom line:how can you cleanly append the unit type (e.g. em
) to the result of a calculation in SASS?
底线:如何将单位类型(例如em
)干净地附加到 SASS 中的计算结果?
回答by cimmanon
The only way to add a unit to a number is via arithmetic.
将单位添加到数字的唯一方法是通过算术。
To perform operations like concatenation (eg. 1 + px
) or interpolation (eg. #{1}px
) will only create a stringthat lookslike a number. Even if you're absolutely 100% certain that you're never going to use your value in another arithmetic operation, you should not do this.
为了执行像拼接操作(如1 + px
)或内插(例如#{1}px
)将只创建一个字符串是看起来像一个数字。即使您绝对 100% 确定您永远不会在另一个算术运算中使用您的值,您也不应该这样做。
More important than not being able to perform arithmetic operations, you won't be able to use them with other functions that expects a number:
比不能执行算术运算更重要的是,您将无法将它们与其他需要数字的函数一起使用:
$foo: 1; // a number
$foo-percent: $foo + '%'; // a string
.bar {
color: darken(blue, $foo-percent); //Error: "1%" is not a number!
}
$amount: "1%" is not a number for `darken'
$amount: "1%" 不是‘变暗’的数字
There is nothing to be gained by casting your numbers to strings. Always use arithmetic (multiplication by 1, or addition by 0) to add a unit:
将数字转换为字符串没有任何好处。始终使用算术(乘以 1 或加以 0)来添加一个单位:
$foo: 1; // a number
$foo-percent: $foo * 1%; // still a number! //or: $foo + 0%
.bar {
color: darken(blue, $foo-percent); //works!
}
Output:
输出:
.bar {
color: #0000fa;
}
Here's a mixin I wrote as part of my Flexbox mixin library that will choke if you pass in a string (for those not familiar with Flexbox, the original specification only allows integers for the box-flex
property. flex: auto
or flex: 30em
cannot be made compatible with the comparable box-flex
property, so the mixin doesn't bother trying)
这是我作为 Flexbox mixin 库的一部分编写的一个 mixin,如果你传入一个字符串,它会阻塞(对于那些不熟悉 Flexbox 的人,原始规范只允许box-flex
属性使用整数。 flex: auto
或者flex: 30em
不能与可比较的box-flex
属性兼容,所以mixin 不费心去尝试)
@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...);
}
回答by Naoise Golden
You can try either of these:
您可以尝试以下任一方法:
font-size: $size * 1px;
or
或者
font-size: $size + unquote("px");
Where $size
is the result of your calculation.
$size
你的计算结果在哪里。
回答by electric_g
Choose the method you prefer
选择您喜欢的方法
$font: 24px;
$base: 16px;
No variables
无变量
.item1 { font-size: #{(24px / 16px)}em; }
Using only variables
仅使用变量
.item2 { font-size: #{$font / $base}em; }
One variable
一变量
.item3 { font-size: #{$font / 16px}em; }
.item4 { font-size: #{24px / $base}em; }
Output for all of them
所有这些的输出
.item1 { font-size: 1.5em; }
.item2 { font-size: 1.5em; }
.item3 { font-size: 1.5em; }
.item4 { font-size: 1.5em; }
The method used is called interpolation #{}
使用的方法称为插值#{}
回答by Ilmari Karonen
I assume the reason you're asking this is because, in the surrounding context, 1 em = 16 px, and you want to use this relationship to convert the target font size from pixels to ems.
我假设你问这个的原因是因为,在周围的上下文中,1 em = 16 px,并且你想使用这种关系将目标字体大小从像素转换为 em。
If so, the rightthing to do is to multiply the font size with the scaling factor 1em / 16px, like this:
如果是这样,正确的做法是将字体大小乘以缩放因子 1em / 16px,如下所示:
$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 molesof 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 massof 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.
这也正是它在物理学中的工作原理:如果有,比如说,50摩尔的水,你想知道它的重量是多少克,你可以将你的水量(= 50 摩尔)乘以摩尔质量水 (≈ 18 g/mol) 以发现您的水样重量为 50 mol × 18 g/mol ≈ 900 克。在 SASS 中将像素转换为 em 的工作方式相同:首先找出每个像素有多少个 em,在您打算使用该规则的上下文中,然后以 px 为单位的大小乘以该比率,以 em 为单位/像素。
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:
附言。当然,如果您要转换的单位具有 SASS 已经知道的固定比率,那么您可以使用“零加技巧”简单地让它自动为您进行转换。例如,如果您想将字体大小从 px 转换为 cm,您可以简单地执行以下操作:
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 firstvalue in the sum. The reason this trick doesn'twork 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.
这是有效的,因为 SASS 允许您将两个以兼容单位(如 px 和 cm)给出的值相加,并将以与总和中的第一个值相同的单位表示结果。这个技巧对 px -> em不起作用的原因是这里的转换因子不是固定的,而是取决于周围的上下文,所以 SASS 不知道如何自动进行转换。
回答by S.Serpooshan
The best way to add a unit, is to use ... * 1em
or ... + 0em
where em
is the unit you want to get:
增加一个单位,最好的办法,就是用... * 1em
或... + 0em
地方em
是你想要得到的单位:
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 numberso 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)!
无需使用unquote
或#{}
在这里(如其他答案中所写)!