如何从Sass混合方程式中删除测量单位? [英] How do you remove units of measurement from a Sass mixin equation?

查看:80
本文介绍了如何从Sass混合方程式中删除测量单位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个非常简单的Sass mixin,用于将像素值转换为rem值(请参阅Jonathan Snook的文章有关使用rems的好处).这是代码:

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;
}

此mixin效果很好,但是我对它的include语法有点不满意.瞧,我宁愿将一个像素值传递给include语句,而不是一个简单的数字.这是一个很小的细节,但是会将语义添加到当前不存在的include语句中.这是我尝试将像素值传递到include语句时得到的:

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;
}

一旦Sass看到将像素值传递到方程式中,它将输出'px'. 我想剥离该度量单位,就像我在JavaScript中使用parseFloat或parseInt一样.在Sass mixin中如何做到这一点?

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?

推荐答案

从数字中删除单位是通过除法完成的,就像在代数中一样.

Removing units from a number is done by division, just like in Algebra.

$base-font-size: 10px;
$rem-ratio: $base-font-size / 1rem;

@mixin rem($key,$px) {
  #{$key}: $px;
  #{$key}: $px/$rem-ratio;
}


// Include syntax
p {
  @include rem(font-size,14px);
}

// Rendered CSS
p {
  font-size: 14px;
  font-size: 1.4rem;
}

Sass中的单位可以视为真实数学中的单位,因此px/px/rem仅用于rem.享受吧!

Units in Sass can be treated as in real math, so px/px/rem goes to just rem. Enjoy it!

这篇关于如何从Sass混合方程式中删除测量单位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆