cssmedia-queries

How to show div when media is print, hide at all other times?


I want to use this to print only the #section-to-print:

@media print {
    body * {
        visibility: hidden;
    }
    #section-to-print, #section-to-print * {
        visibility: visible;
    }
    #section-to-print {
        position: absolute;
        left: 0;
        top: 0;
    }
}

How do I extend this to hide the #section-to-print when it is being displayed on the screen? In other words, it would only be visible when the media is print.


Solution

  • Set it to visibility: hidden, then @media print can override it.

    #section-to-print, #section-to-print * {
        visibility: hidden;
    }
    @media print {
        body * {
            visibility: hidden;
        }
        #section-to-print, #section-to-print * {
            visibility: visible;
        }
        #section-to-print {
            position: absolute;
            left: 0;
            top: 0;
        }
    }