如何编写适用于媒体打印和特定情况的CSS样式,使用SCSS

3

我有一个特殊的情况,我的样式需要同时应用于打印媒体和当 <body> 具有特殊类以进行检测,我们称之为 .is-pdf-mode 类。

在我的 SCSS 中,我尝试使用 @content 避免重复 CSS 代码,但是生成的 CSS 并没有正确地生成一个选择器用于 <body> 情况。我不能在这个 mixin 中使用 & 选择器。到目前为止,这是我的尝试。

SCSS:

@mixin query-print {
  @media print {
    @content;
  }

  .body.is-pdf-mode {
    @content;
  }
}

.box {
  width: 200px;
  height: 200px;
  background: lightsalmon;
  margin: 15px;

  @include query-print {
    background: green;
  }
}

@media print {
// Default styling only apply for print
html,
body,
page[size="A4"] {
    padding:0px;
    margin:0px;
    width: 210mm;
    height: 297mm;
}

body {
  -webkit-print-color-adjust: exact !important;
  zoom: 100%;
}

}

HTML:

<div class="body">
  <div class="box">
    hello
  </div>
</div>

<div class="body is-pdf-mode">
  <div class="box">
    hello
  </div>
</div>

我了解通过在mixin中编写.body.is-pdf-mode,这意味着.box .body.is-pdf-mode,而应该改为.body.is-pdf-mode .box。那么,在这种情况下,正确的CSS编写方式是什么?
Codepen尝试:https://codepen.io/DieByMacro/pen/xoLNpE 更新1:在query-print mixin中重新编写我的CSS:
如果我像这样写:
.box {
  width: 200px;
  height: 200px;
  background: lightsalmon;
  margin: 15px;
}

@include query-print {
.box {
  background: green;
}
}

显然这样做可以实现,但在我的真实项目中,我们采用在选择器内使用@include mixin的方法。通过应用此策略,意味着需要重新编写许多选择器,因此我认为这是当没有其他选择时的最后手段。

谢谢。

1个回答

2

You can use @at-root and &:

@mixin query-print {
  @media print {
    @content;
  }

  @at-root.body.is-pdf-mode #{&} {
    @content;
  }
}

使用您的示例,它将返回:

@media print {
  .box {
    background: green;
  }
}

.body.is-pdf-mode .box {
  background: green;
}

SASS @at-root 文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接