0

I need to apply some styles to a div for printing. I can use a media query @media print {} to accomplish this easily. But I also sometimes need to apply the same styles on the browser itself, before the print dialog is opened. I'm trying to do this by adding a div .print-view to the page. But can't find a way to do it without code duplication.

I've tried this, but it's invalid css:

.print-view, @media print {
  .grey-background {
    background-color: white;
  }
}

I've also tried this (scss), but it causes an error @extend may only be used within style rules.

.print-view {
  .grey-background {
    background-color: white;
  }
}

@media print {
  @extend .print-view;
}

Is there some other way for me to accomplish this?

Edit: changed sample code to more accurately reflect what I'm trying to do

Benjamin
  • 1,372
  • 2
  • 12
  • 20
  • you cannot apply a style to media query to start with. You can apply a style to *only* selector that can be inside media queries – Temani Afif Jan 27 '22 at 20:49
  • @TemaniAfif Ah, you are correct. I've updated the sample code to more accurately reflect what I'm trying to do. – Benjamin Jan 27 '22 at 20:53
  • I don't think so, at least not with @extend. You could use a mixin to apply those styles to both the browser and print query, though. It wouldn't make it entirely DRY, like you said you're trying to do, but there'd be less bloat in the scss file. – yerme Jan 27 '22 at 20:59

1 Answers1

0

Found the answer here. @include can be used to add a mixin into both a media query and a normal selector.

@mixin print {
  .grey-background {
    background-color: white;
  }
}

.print-view {
  @include print;
}

@media print {
  @include print;
}

This compiles to the following css:

.print-view .grey-background {
  background-color: white;
}

@media print {
  .grey-background {
    background-color: white;
  }
}
Benjamin
  • 1,372
  • 2
  • 12
  • 20