sass px2rem_带有Sass的REM到PX浏览器功能

sass px2rem

Performance is a key skill for front-end developers today. New CSS3 and HTML5 features help improve our apps but sometimes these features aren't well supported. This is where Graceful Degradation comes in. You want to leverage the extended features of new browsers but can't afford to ignore support for legacy browsers. I recently started a new project where IE8 support was required. Due to cascade problems when using nested 'EM' units, I decided to start my project using the useful 'REM' units, which are easier to understand and maintain. The main problem with this approach is that IE8- doesn't include support for 'REM' units. Ultimately, I needed to create a fallback for this scenario: in this case, a 'PX' unit fallback.

性能是当今前端开发人员的一项关键技能。 CSS3和HTML5的新功能有助于改善我们的应用程序,但有时这些功能并没有得到很好的支持。 这就是Graceful Degradation出现的地方。您想利用新浏览器的扩展功能,但不能忽视对旧版浏览器的支持。 我最近开始了一个需要IE8支持的新项目。 由于在使用嵌套的“ EM”单元时存在级联问题,我决定使用有用的“ REM”单元开始我的项目,该单元更易于理解和维护。 这种方法的主要问题是IE8-不包括对“ REM”单元的支持。 最终,我需要为这种情况创建一个后备:在这种情况下,是一个“ PX”单元后备。

性能和编码速度 (Performance and Coding Speed)

You'll find a lot of helpful resources on the web for the topic 'REM to PX Mixins' (see related articles) which I've used as part of the research for this article. The majority of these rely on the same technique: using a Sass Mixin which generates the CSS property twice, for example :

在Web上您可以找到很多有用的资源,主题为“ REM到PX Mixins”(请参阅​​相关文章),我已将其用作本文研究的一部分。 其中大多数依赖于相同的技术:使用Sass Mixin生成两次CSS属性,例如:

SCSS: (SCSS:)

.header  {
    @include rempx(margin, 1rem 2rem);
}


outputs to:

输出到:

CSS: (CSS:)

.header  {
	margin:16px 32px; /* Fallback */
	margin:1rem 2rem;
}


The main problem with this is that every CSS property using this mixin is duplicated, and your overall CSS weight will grow. This technique serves two properties instead of one, and falls back to the first if 'REM' units aren't supported by the browser. It's not very clean, but it's smart and easy to maintain. Because we know 'REM' units aren't supported in IE8-, what if we served two different stylesheets?

这样做的主要问题是,使用该mixin的每个CSS属性都会重复,并且您CSS总权重也会增加。 此技术提供两个属性而不是一个属性,并且如果浏览器不支持“ REM”单元,则会退回到第一个属性。 它不是很干净,但是很聪明并且易于维护。 因为我们知道IE8-不支持“ REM”单元,所以如果我们提供两个不同的样式表怎么办?

The second problem with the above method is typing-speed. Typing @include rempx(property, values) each time you want to add a new CSS property isn't optimal.

上述方法的第二个问题是打字速度。 每次要添加新CSS属性时@include rempx(property, values)键入@include rempx(property, values)都不是最佳选择。

提供不同的样式表 (Serving Different Stylesheets)

Our first goal is to have two separates stylesheets:

我们的首要目标是拥有两个单独的样式表:

  • A 'main.css' file for standards Browsers, using 'REM' units.

    标准浏览器的“ main.css”文件,使用“ REM”单位。
  • A 'main-ie.css' file for IE8-, using 'PX' units.

    IE8-的“ main-ie.css”文件,使用“ PX”单元。

(both of these files will have exactly the same CSS contents, only the units are different)

(这两个文件CSS内容完全相同,只是单位不同)

Nicolas Gallagher shows us how to serve a basic CSS for standard browsers and a different CSS for IE8- using this code:

Nicolas Gallagher向我们展示了如何使用以下代码为标准浏览器提供基本CSS,为IE8提供不同CSS:


<!--[if (gt IE 8) | (IEMobile)]><!-->
      <link rel="stylesheet" href="/css/main.css">
<!--<![endif]-->

<!--[if (lt IE 9) & (!IEMobile)]>
      <link rel="stylesheet" href="/css/main-ie.css">
<![endif]-->


Standard browsers will download the 'main.css' only, and IE8- will download the 'main-ie.css' only. This ensures that the client doesn't have to download both css files.

标准浏览器将仅下载“ main.css”,而IE8-将仅下载“ main-ie.css”。 这样可以确保客户端不必下载两个CSS文件。

Our second goal is to keep the "@mixin" technique so that we only have to maintain one file.

我们的第二个目标是保留“ @mixin”技术,以便我们仅需维护一个文件。

抢救! (Sass to the Rescue!)

Now that we know how to serve different stylesheets, we need to generate two CSS files. This is were Sass comes in. To keep the example simple I won't use a special file structure for Sass, just a bunch of .SCSS files. Here is the structure for our example:

现在我们知道了如何提供不同的样式表,我们需要生成两个CSS文件。 这是Sass进来的。为了简化示例,我不会为Sass使用特殊的文件结构,而只是使用一堆.SCSS文件。 这是我们示例的结构:

  • An empty 'css' folder.

    空的“ css”文件夹。
  • A 'sass' folder with four files:

    “ sass”文件夹,其中包含四个文件:

    • main.scss

      main.scss
    • main-ie.scss

      主ie.scss
    • _functions.scss

      _functions.scss
    • _module-example.scss

      _module-example.scss

MAIN.SCSS: (MAIN.SCSS:)


// config
$px-only:false;

// import sass functions
@import "functions";

// import site modules
@import "module-example.scss";


MAIN-IE.SCSS: (MAIN-IE.SCSS:)


// config
$px-only:true;

// import sass functions
@import "functions";

// import site modules
@import "module-example.scss";


_FUNCTIONS.SCSS: (_FUNCTIONS.SCSS:)


$pixelBase : 16; /* 1 */


@function parseInt($n) {
    @return $n / ($n * 0 + 1); /* 2 */
}


@function u($values){ /* 3 */


    $list: (); /* 4 */


    @each $value in $values { /* 5 */
        
        @if (type-of($value) == "number") and ($value != 0) { /* 6 */


            $unit : unit($value);     /* 7 */
            $val  : parseInt($value); /* 2 */


            @if ($px-only) and ($unit == 'rem') { /* 8 */
                $list: append($list, ($val * $pixelBase) + px); /* 8 */
            }


            @else if($unit == 'px') or ($unit == 'rem'){ /* 9 */
                $list: append($list, $value); /* 9 */
            }


            @else {
                @warn 'There is no unit conversion for "#{$unit}"'; /* 10 */
            }


        }@else {
            $list: append($list, $value); /* 11 */
        }


    }


    @return $list(); /* 12 */


}


它是如何工作的 ? 说明。 (How Does it Work ? Explanations.)

The variable $px-only isn't scoped in the 'main.css' or 'main-ie.scss' only. All imported files are impacted by the value of $px-only. When u() function is called, it refers to the value of $px-only declared in the 'main.scss' or 'main-ie.scss' files. This Sass unit function must be imported before the other modules in order to work.

变量$ px-only仅在'main.css'或'main-ie.scss'中不起作用。 所有导入的文件均受仅$ px的值影响。 调用u()函数时,它引用的是在“ main.scss”或“ main-ie.scss”文件中声明的仅$ px的值。 必须先导入此Sass单元功能,然后才能使用其他模块。

功能说明: (Function Explanations:)

  1. This variable refers to the default browser's font-size, and 1rem = 16px. For more maintainability, we store the value in a variable in order to reuse it or to change it easily.

    此变量引用默认浏览器的字体大小,并且1rem = 16px。 为了提高可维护性,我们将值存储在变量中,以便重复使用或轻松更改它。
  2. This function returns a number from a given string, thanks Hugo for it! http://hugogiraudel.com/2013/03/18/ultimate-rem-mixin/

    这个函数从给定的字符串返回一个数字,感谢雨果! http://hugogiraudel.com/2013/03/18/ultimate-rem-mixin/
  3. We called our function u because it's faster and easy to type. 'u' also stands for 'unit'. This function takes one argument which is the CSS values with multiples REM or PX numbers, e.g u('5rem 2px').

    我们将函数称为u,是因为它可以更快,更容易键入。 “ u”也代表“单位”。 此函数采用一个参数,该参数是具有多个REM或PX数字CSS值,例如u('5rem 2px')。
  4. We define a new list, where we'll store new values.

    我们定义一个新列表,我们将在其中存储新值。
  5. For each value passed in $values argument, test the current value and store it in the $list array.

    对于传入$ values参数的每个值,测试当前值并将其存储在$ list数组中。
  6. Test if the current value is a number and if that value isn't equal to 0.

    测试当前值是否为数字,并且该值不等于0。
  7. This Sass function returns the unit associated with a number. In our case, 'PX' or 'REM'.

    此Sass函数返回与数字关联的单位。 在我们的情况下,为“ PX”或“ REM”。
  8. First condition: if 'pixels only' mode is active and unit value is 'REM', convert 'REM' value in pixels and push it into $list array.

    第一个条件:如果“仅像素”模式处于活动状态,并且单位值为“ REM”,则将“ REM”值转换为像素并将其推入$ list数组。
  9. Second condition: else if the units are 'PX' or 'REM' we just push value into list.

    第二个条件:否则,如果单位是“ PX”或“ REM”,我们只需将值推入列表。
  10. If the first and second conditions fails, we throw a warning in Sass console.

    如果第一个条件和第二个条件失败,我们将在Sass控制台中引发警告。
  11. If the first condition on 6) fails, just push the current value in the list.

    如果6)的第一个条件失败,则只需将当前值推入列表即可。
  12. Then, we return the whole list as a clean CSS string values.

    然后,我们以干净CSS字符串值返回整个列表。

用法 (Usage)

_MODULE-EXAMPLE.SCSS: (_MODULE-EXAMPLE.SCSS:)

.main-header {
    margin:u(1rem auto 10px);
    padding-bottom:u(0.25rem);
    font-size:u(0.875rem);
}


Outputs to:

输出到:

MAIN.CSS: (MAIN.CSS:)

.main-header {
    margin: 1rem auto 10px;
    padding-bottom: 0.25rem;
    font-size: 0.875rem;
}


MAIN-IE.CSS: (MAIN-IE.CSS:)

.main-header {
    margin: 16px auto 10px;
    padding-bottom: 4px;
    font-size: 14px;
}


优点缺点 (Pros & Cons)

优点 (Pros)

  • Easy to maintain: Just edit your code once, and two separate stylesheets will be generated.

    易于维护:只需编辑一次代码,就会生成两个单独的样式表。
  • Easy to read: Your final CSS is clear and without unused properties.

    易于阅读:您的最终CSS很清晰,没有未使用的属性。
  • Lower file size: Your final CSS is lighter.

    较小的文件大小:最终CSS更轻巧。
  • Faster to develop: Just type u() to generate the final units.

    开发速度更快:只需键入u()即可生成最终单位。

缺点 (Cons)

  • Needs a hack in the <head> to serve the right stylesheet.

    需要<head>中的技巧来提供正确的样式表。

I'd love to get your feedback on this technique, and share any ideas you might have on how it could be improved!

我很乐意收到您对此技术的反馈,并分享您对如何改进它的任何想法!

相关文章 (Related Articles)

This code is also available on GitHub and Bower.

该代码在GitHub和Bower上也可用。

翻译自: https://davidwalsh.name/rem-px-browser-function-sass

sass px2rem

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值