首页 文章

SASS:REM到PX mixin的样式相同

提问于
浏览
2

我've been using the great REM to PX mixin function from David Walsh'的博客 - http://davidwalsh.name/rem-px-browser-function-sass - 见下文:

$px-only:false;  

$pixelBase : 16; /* 1 */

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

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

      $list: (); /* 4 */

      @each $value in $values { /* 5 */

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

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

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

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

      }

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

}

这允许您编写以下内容:

.style {
    margin:u(1rem 2rem 20px 3rem);
    padding-bottom:u(0.25rem);
    font-size:u(0.875rem);
}

如果$ px-only = false,则输出以下内容:

.style {
    margin: 1rem 2rem 20px 3rem;
    padding-bottom: 0.25rem;
    font-size: 0.875rem;
}

如果$ px-only = true,则在IE样式表中如下:

.style {
    margin: 16px 32px 20px 48px;
    padding-bottom: 4px;
    font-size: 14px;
}

我想避免创建一个单独的样式表来输出IE特定的像素回退并定位body类,如下所示:

<!--[if lt IE 7 ]> <body class="ie6 "> <![endif]-->
<!--[if IE 7 ]>    <body class="ie7 "> <![endif]-->
<!--[if IE 8 ]>    <body class="ie8 "> <![endif]--> 
<!--[if !IE]><!--> <body> <!--<![endif]-->

有没有人对如何实现这一点有任何想法,所以在同一样式表中输出类似下面的代码?

.style {
    margin: 1rem 2rem 20px 3rem;
    padding-bottom: 0.25rem;
    font-size: 0.875rem;
}

.ie8 .style {
    margin: 16px 32px 20px 48px;
    padding-bottom: 4px;
    font-size: 14px;
}

任何帮助都会很棒!

1 回答

  • 1

    只使用功能,你无法做到你所要求的 . 函数用于返回单个值 . 你必须使用mixins来获得所需的效果 . 另外,当你可以利用浏览器解析CSS的方式时,拥有一个单独的选择器绝对没有好处(同样,你所要求的工作所涉及的努力根本不值得) .

    您想要的输出应如下所示:

    .style {
        margin: 16px 32px 20px 48px;
        margin: 1rem 2rem 20px 3rem;
        padding-bottom: 4px;
        padding-bottom: 0.25rem;
        font-size: 14px;
        font-size: 0.875rem;
    }
    

    这意味着你需要这样的mixin:

    @mixin rem($propertie, $value) {
      #{$propertie}: $value;
      #{$propertie}: calculateRem($value);
    }
    

    见:Automate pixel fallback using REM units throughout a project

相关问题