3

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

cdMinix
  • 655
  • 1
  • 7
  • 29
  • 3
    This occurs because the direct child element of body, has a selector that sets it to display: none;. It does not matter that the child of that element then has a display: inline, it will always be hidden because of it's parent. – Shane Aug 05 '15 at 13:54
  • @Shane But is there a way to display an element even when its parent has ``display`` set to ``none``? – cdMinix Aug 05 '15 at 13:56
  • To my knowledge there is no such option to do this with `display: none;` I did however find this answer: http://stackoverflow.com/a/12956970/3270185 that tries to solve it with the `visibility` property. Would this be an option for you? – Shane Aug 05 '15 at 13:58
  • @Shane I'll try using visibility, but does it remove elements from the document flow? – cdMinix Aug 05 '15 at 14:00
  • There is no selector that allows selection of parent objects, and traversing through the DOM (with perhaps Javascript) would not be performance friendly. – Shane Aug 05 '15 at 14:03

1 Answers1

3

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.

Shane
  • 336
  • 1
  • 11
  • Be sure that if you do this that you use the `aria-hidden="true"` attribute on the elements that are print only, otherwise you may create accessibility issues. – maxshuty Apr 05 '22 at 17:14