Search code examples
printinglessmedia-queries

Add css when @media print using less mixin and guard expressions


I want to avoid duplication in my code. Is it possible to write something like this in LESS?

.print when (@media print = true) {
    background: @heading-background-color !important;
    -webkit-print-color-adjust: exact;
 }

  .header-month {
    .print
    background: @heading-background-color;
    font-weight: bold;
  }

Instead of:

@media print {
  .header-month {
    background: @heading-background-color !important;
    -webkit-print-color-adjust: exact;
  }
}

  .header-month {
    background: @heading-background-color;
    font-weight: bold;
  }

It doesn't look like an improvement here. But I'm working with multiple classes and need to do this for all of them.. So maybe an alternative if this is not possible?


Solution

  • Less @media can be nested in a rule so you can define such .print mixin as:

    .print() {
        @media print {
            background: @heading-background-color !important;
            -webkit-print-color-adjust: exact;
        }
    }
    
    // usage:
    .header-month {
        .print();
        background: @heading-background-color;
        font-weight: bold;
    }
    

    Also see "Passing Rulesets to Mixins" for a more complex stuff.