How to only show certain parts with CSS for Print?

A simple way:

<style>
    .print-only{
        display: none;
    }

    @media print {
        .no-print {
            display: none;
        }

        .print-only{
            display: block;
        }
}
</style>

Start here. But basically what you are thinking is the correct approach.

Thanks, Now my question is actually becoming: How do I apply CSS to a class AND ALL OF ITS DESCENDANT ELEMENTS? So that I can apply "display:block" to whatever is in the "printable" zones.

If an element is set to display:none; all its children will be hidden as well. But in any case. If you want a style to apply to all children of something else, you do the following:

.printable * {
   display: block;
}

That would apply the style to all children of the "printable" zone.


I got here because I was curious about printing a chart generated by chart.js. I wanted to just print the chart directly from the page (with a button that does a 'window.print') without all of the other content of the page.

So, I got closer by using the technique from the answer here: Why can't I override display property applied via an asterisk? .

You have to apply the 'asterisk' to the 'body' element, not just by itself. So, using the example CSS that the OP (Nathan) added to the question, I changed it to this:

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

Then adding that 'printable' class to the chart itself, as in

<canvas id="myChart" class="printable" width="400" height="400"></canvas>

Which removed all page elements on the printed output except the chart when the 'print' button is clicked (via this):

<script>
    myChart.render();
    document.getElementById("printChart").addEventListener("click",function(){
        window.print();
    });     
</script>

So, perhaps this will help anyone that gets to this question via the googles.


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>