Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only print elements with a certain class in nested divs

It is possible to hide everything on a page and only show elements with a certain class. Using the following css, only elements with the print-me clas should be printed.

@media print {
  .print-me, .print-me * {
    display: inline;
  }
  body * {
    display: none;
  }
}

But this only works when print-me elements are direct children of body. When there is another element wrapped around the classes, as in the following html, nothing is displayed when printing.

<html>
  <body>
    <div>  
      <div class="print-me">
        <p>This text should be printed, but isn't.</p>
      </div>
      <div>
        <p>This text isn't printed.</p>
      </div>
    </div>
  </body>
</html>

Codepen; Debug View

like image 889
cdMinix Avatar asked Sep 14 '25 07:09

cdMinix


1 Answers

As I suggested in the comments, try it with the following css:

@media print {
  .print-me, .print-me * {
    visibility: visible;
  }
  body * {
    visibility: hidden;
  }
}

This seems to do what you're expecting.

like image 71
Shane Avatar answered Sep 16 '25 00:09

Shane