Sass 计算减速下降 Chrome

Sass calc decleration dropped Chrome

我正在使用 Sass 编写一个简单的网格布局。我正在尝试使用 calc() 来确定相对单位的宽度 %。为了测试样式,我使用了一个简单的 HTML 文件。

问题:在 Chrome 上使用开发工具检查结果表明 calc() 调用的宽度声明被丢弃为 Invalid property value。这是代码:

src.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="X-UA Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width initial-scale=1.0">
        <link rel="stylesheet" type="text/css" href="./../css/12grid_rwd.css">
    </head>
    <body>
        <main class="grid_1" role="main">
            <!--<header class="grid_12" role="banner">Header</header>
            <nav class="grid_3" role="navigation">Nav</nav>
            <section class="grid_9">Content</section>
            <footer class="grid_12" role="contentinfo">Footer</footer> -->
        </main>
    </body>
</html>

src.scss

$context-width: 1200;
// Grid >> 12 Columns
.grid {
    &_1 { width: calc(calc(80/#{$context-width})*100); }
}

生成css:

.grid_1 {
  width: calc(calc(80/1200)*100); }

calc() 调用不能嵌套,它需要表达式来计算,这就是你的 属性 被浏览器丢弃的原因。

此外,由于您的表达式包含纯数学 - 它可以由 Sass 本身计算。此外,从您的表达式来看,您似乎希望结果值是容器宽度的百分比,在这种情况下,您可以使用 Sass:

中的 percentage() 函数
$context-width: 1200;
$column-width: 80;
// Grid >> 12 Columns
.grid {
  @for $n from 1 through 12 {
    &_#{$n} { 
      width: percentage($column-width * $n/$context-width); 
    }
  }
}

您可以在 Sassmeister 上玩这个例子。

按照@Flying 的建议,我能够实现我想要的逻辑。代码更容易理解和调试。

目标:拥有一个 1280 像素的网格系统,容器边距为 20px,网格上填充为 20px。请注意,这些边距和填充属性仅适用于左侧和右侧(每侧 10px)。从第一个网格开始,class grid_1,在 80px,grid_2 将是 80*2 + 20*(2-1),其中 80 is the fixed column width, 2 is the grid number, 20 is the padding 等等。 scss代码如下:

src.scss

$context-width: 1200;
$column-width: 80;
$fixed-gutter: 20;

// Grid >> 12 Columns

@mixin width-calc($n) {
  @if $n == 1{
    width: percentage(($column-width * $n)/$context-width);
  }
  @else {
    $c: $column-width * $n + ($fixed-gutter * ($n - 1));
    width: percentage(($c)/$context-width);
  }
}

.grid {
  @for $n from 1 through 12 {
    &_#{$n} {
      @include width-calc($n);
    }
  }
}

生成的css:

.grid_1 {
  width: 6.66667%;
}
.grid_2 {
  width: 15%;
}
.grid_3 {
  width: 23.33333%;
}
.grid_4 {
  width: 31.66667%;
}
.grid_5 {
  width: 40%;
}
.grid_6 {
  width: 48.33333%;
}
.grid_7 {
  width: 56.66667%;
}
.grid_8 {
  width: 65%;
}
.grid_9 {
  width: 73.33333%;
}
.grid_10 {
  width: 81.66667%;
}
.grid_11 {
  width: 90%;
}
.grid_12 {
  width: 98.33333%;
}