Sass mixin 输出 css 与计算输出不同,而不是手动简化



我有以下 HTML:

  <div class="row">
    <div class="col-1-of-3">Col 1 of 3</div>
    <div class="col-2-of-3">Col 2 of 3</div>
  </div>

和以下 SCSS:

$gutter-horizontal: 6rem;
@mixin clearfix {
  &::after {
    content: "";
    display: table;
    clear: both;
  }
}
@mixin colWidth($dim, $sub: 1) {
  width: calc(
    #{$sub} * (100% - (#{$dim}-1) * #{$gutter-horizontal}) / #{$dim} +
      (#{$sub}-1) * #{$gutter-horizontal}
  );
}
.row {
  max-width: $grid-width;
  background: #eee;
  margin: 0 auto;
  &:not(:last-child) {
    margin-bottom: $gutter-vertical;
  }
  @include clearfix;
  [class^="col-"] {
    float: left;
    background: red;
    &:not(:last-child) {
      margin-right: $gutter-horizontal;
    }
  }
  .col-1-of-3 {
    width: calc((100% - 2 * #{$gutter-horizontal}) / 3);
  }
  .col-2-of-3 {
    @include colWidth(3, 2);
  }

我试图概括:

.col-2-of-3 {
  width: calc(
    2 * ((100% - 2 * #{$gutter-horizontal}) / 3) + #{$gutter-horizontal}
  );
}

渲染时,inspect 告诉我我的混合产量:

width: calc( 2 * (100% - (3-1) * 6rem) / 3 + (2-1) * 6rem);

简化为:

width: calc( 2 * (100% - 2 * 6rem) / 3 + 6rem);

而直接方法检查:

width: calc( 2 * ((100% - 2 * 6rem) / 3) + 6rem);

虽然这些在操作顺序上是相同的,但根据检查的最终宽度是不同的。

对我来说,他们分别是614和594。

为什么会有差异?

谢谢。

我认为这里的问题是space

如果你的mixin给你这个输出:

width: calc( 2 * (100% - (3-1) * 6rem) / 3 + (2-1) * 6rem);

浏览器会返回错误,因为您必须在每个运算符之间留出空格:

width: calc( 2 * (100% - (3 - 1) * 6rem) / 3 + (2 - 1) * 6rem);

我创建了一个示例。在第一种情况下,我使用了您的mixin结果和直接方法:

.col-1-of-3 {
  width: calc(2 * (100% - (3-1) * 6rem) / 3 + (2-1) * 6rem);
  background-color:#ff0000;
}
.col-2-of-3 {
  width: calc(2 * ((100% - 2 * 6rem) / 3) + 6rem);
  background-color:#00ff00;
}
<div class="row">
    <div class="col-1-of-3">Col 1 of 3</div>
    <div class="col-2-of-3">Col 2 of 3</div>
</div>

宽度是不同的,因为对于您的mixin结果,浏览器无法理解您的(3-1)(2-1)操作。但是如果我们在运算符之间放置空格,mixin 结果和直接方法会给我们相同的结果:

.col-1-of-3 {
  width: calc(2 * (100% - (3 - 1) * 6rem) / 3 + (2 - 1) * 6rem);
  background-color:#ff0000;
}
.col-2-of-3 {
  width: calc(2 * ((100% - 2 * 6rem) / 3) + 6rem);
  background-color:#00ff00;
}
<div class="row">
    <div class="col-1-of-3">Col 1 of 3</div>
    <div class="col-2-of-3">Col 2 of 3</div>
</div>

我认为这就是这种差异的原因。

最新更新