4

I'm building a html report using media query print. Up to this point everything was working well, until I added a "Print" button to the page that performs the JavaScript command "window.print()". By using the shortcut (Ctrl + P) my web browser shows the print preview according to the media print, however, when I click on the "Print" button, the media query rules is been ignored.

Does anyone now how to fix it?

@media print {

  @page { 
    size: A4; 
    margin: 1cm
  }

  body * {
    visibility: hidden;
  }

  .printArea, .printArea * {
    visibility: visible;
  }

  .spacePrint{
    border: 1px solid #ccc;
  }

  .printArea {
    margin-top :0;
    position: fixed;
    left: 0;
    top: 0px;
  }
}
2
  • Can you show your implementation of the print button? Commented Mar 8, 2016 at 3:26
  • I'm experiencing the same issue in Chrome using React and styled-components Commented May 10, 2019 at 10:23

2 Answers 2

3

It does work ... here's a sample.

Tested in Chrome, IE11, and Edge.

function doPrint() {

  window.print();

}
@media print {
  @page {
    size: A4;
    margin: 5cm;
  }
  body * {
    display: none;
  }
  body h1 {
    display: block;
  }
}
<body>
  <h1>Print Hello World!</h1>
  <div>You cannot print me!</div>
  <button onclick="doPrint()">Print Me!</button>
</body>

Sign up to request clarification or add additional context in comments.

Comments

0

This can be fixed by waiting for the event queue to clear before calling window.print(). This code worked for me:

setTimeout(() => window.print(), 0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.