How to only show certain parts with CSS for Print?

Viewed 73946

I have a page with lots of data, tables and content. I want to make a print version that will only display very few selected things.

Instead of writing another page just for printing, I was reading about CSS's feature for "@media print".

First, what browsers support it? Since this is an internal feature, it's OK if only the latest browsers support it.

I was thinking of tagging a few DOM elements with a "printable" class, and basically apply "display:none" to everything except those elements with the "printable" class. Is that doable?

How do I achieve this?

EDIT: This is what I have so far:

<style type="text/css">
@media print {
    * {display:none;}
    .printable, .printable > * {display:block;}
}
</style>

But it hides everything. How do I make those "printable" elements visible?

EDIT: Trying now the negative approach

<style type="text/css">
@media print {
    body *:not(.printable *) {display:none;}
}
</style>

This looks good in theory, however it doesn't work. Maybe "not" doesn't support advanced css ...

7 Answers

If you want to display some links etc. when in the browser, that you don't want to be printed. Furthermore you have some logos and letterhead info that only should go on the printed page. This seems to work fine:

Example:

CSS:

@media print {
  .noPrint {
      display:none;
  }
}
@media screen {
   .onlyPrint {
       display: none;
   }
}

HTML:

<div class="noPrint" id="this_is_not_printed"  >
   <a href=links.html>
</div>
<div class="onlyPrint"  id="this_is_only_seen_on_printer" >
   <img scr=logo.png >
   <img scr=letterhead.png >
</div>

Came across the same question recently and for me, this solution works just perfect:

@media print {

    * {
        visibility: hidden;
    }

    .printable {
        visibility: visible;
        position: absolute;
        top: 0;
        left: 0;
        padding: 10mm;
    }

    .printable * {
        visibility: visible;
    }
}

Since visibility: hidden doesn't remove elements, as display: none does, it is possible to change it for desired elements separately.

Related