【问题标题】:SCSS how to write CSS styling applies for both media print and a specific caseSCSS 如何编写 CSS 样式适用于媒体打印和特定案例
【发布时间】:2019-06-26 17:17:34
【问题描述】:

我有一个特殊情况,我的样式需要同时应用于打印媒体,当 <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。应用这种策略,就意味着要重写很多选择器,所以我认为这将是我在没有其他选择时的最后手段。

谢谢,

【问题讨论】:

    标签: css printing sass selector responsive


    【解决方案1】:

    您可以使用@at-root&amp;

    @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 documentation

    【讨论】:

      猜你喜欢
      • 2020-11-23
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 2018-01-07
      • 2016-01-07
      • 1970-01-01
      相关资源
      最近更新 更多