如何从 Sass mixin 方程中删除测量单位?
我编写了一个非常简单的 Sass mixin,用于将像素值转换为 rem 值(请参阅 Jonathan Snook 的 关于好处的文章使用 rems)。这是代码:
// Mixin Code
$base_font_size: 10; // 10px
@mixin rem($key,$px) {
#{$key}: #{$px}px;
#{$key}: #{$px/$base_font_size}rem;
}
// Include syntax
p {
@include rem(font-size,14);
}
// Rendered CSS
p {
font-size: 14px;
font-size: 1.4rem;
}
这个 mixin 工作得很好,但我对它的包含语法有点不满意。看,我宁愿将像素值传递到 include 语句中,而不是简单的数字。这是一个小细节,但它会为当前不存在的 include 语句添加语义。以下是当我尝试将像素值传递到 include 语句中时得到的结果:
// Include syntax
p {
@include rem(font-size,14px);
}
// Rendered CSS
p {
font-size: 14pxpx;
font-size: 1.4pxrem;
}
一旦 Sass 看到像素值被传递到方程中,它就会输出“px”。 我想去掉该测量单位,就像我在 JavaScript 中使用 parseFloat 或 parseInt 一样。在 Sass mixin 中如何做到这一点?
I've written a very simple Sass mixin for converting pixel values into rem values (see Jonathan Snook's article on the benefits of using rems). Here's the code:
// Mixin Code
$base_font_size: 10; // 10px
@mixin rem($key,$px) {
#{$key}: #{$px}px;
#{$key}: #{$px/$base_font_size}rem;
}
// Include syntax
p {
@include rem(font-size,14);
}
// Rendered CSS
p {
font-size: 14px;
font-size: 1.4rem;
}
This mixin works quite well, but I'm a bit unsatisfied with the include syntax for it. See, I would much rather pass a pixel value into the include statement instead of a simple number. This is a small detail, but it would add semantic meaning to the include statement that currently doesn't exist. Here's what I get when I try to pass a pixel value into the include statement:
// Include syntax
p {
@include rem(font-size,14px);
}
// Rendered CSS
p {
font-size: 14pxpx;
font-size: 1.4pxrem;
}
Once Sass sees a pixel value being passed into an equation, it outputs the 'px'. I want to strip that unit of measure out as if I were using parseFloat or parseInt in JavaScript. How does one do so inside of a Sass mixin?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是您可以使用的功能。基于 Foundation 全局辅助函数。
使用示例:
Here is a function you could use. Based of Foundation global helper functions.
Sample use:
从数字中删除单位是通过除法完成的,就像代数中一样。
Sass 中的单位可以视为实际数学中的单位,因此 px/px/rem 变为 rem。好好享受!
Removing units from a number is done by division, just like in Algebra.
Units in Sass can be treated as in real math, so px/px/rem goes to just rem. Enjoy it!