0

I have the following HTML with an inline style of visibility:hidden.I would like to print the element when ctrl+p . It works with display:none but I do not want to use it as I would like the element to take up space on the page.

Following is my implementation

<div
    className="d-print-block mt-2"
    style={{
        alignItems: 'flex-start',
        marginBottom: '1rem',
        visibility: 'hidden' // changing it to display:none works fine
    }}
>
    <div className="col-12">
        <div>This is hidden but needs to be printed</div>
    </div>
</div>
Erick
  • 1,098
  • 10
  • 21
  • 2
    you may have a css rule that sets the visibility css property of that element inside a media query for print https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries#targeting_media_types. Something like `@media print { #idselector{visibility: visible;} } ` Anyway I'm confused hearing that if it had set `display: none` it was visible in the print – Diego D Jan 26 '23 at 08:19
  • I think you can use jQuery to detect the ctrl+p event and then change the visibility style of the element to 'visible'. – Gihan Jan 26 '23 at 08:19
  • 1
    @DiegoD : setting it to display:none shows up because of the class `d-print-block`. – Erick Jan 26 '23 at 08:20
  • with jQuery $(document).on('keydown', function(e) { if (e.ctrlKey && e.keyCode === 80) { // detect ctrl+p $('.d-print-block').css('visibility', 'visible'); } }); – Gihan Jan 26 '23 at 08:22
  • 1
    @Gihan it's a waste using javascript to set the style of elements when you are going to print. It will also change the view on screen and there's a much better way using css alone as suggested already – Diego D Jan 26 '23 at 08:25

1 Answers1

3

Use @media print to override visibility: hidden:

HTML

<div
    class="d-print-block mt-2 hide-for-print"
>
    <div class="col-12">
        <div>This is hidden but needs to be printed</div>
    </div>
</div>

CSS

  .hide-for-print {
    visibility: hidden;
  }

  @media print {
    .hide-for-print {
      visibility: visible;
    }
  }

CodePen

Tomáš Hübelbauer
  • 9,179
  • 14
  • 63
  • 125