79774877

Date: 2025-09-25 13:24:15
Score: 1
Natty:
Report link

As far as I can tell, a general purpose solution to the original question cannot exist. C3roe brought up a good point in the comments: for any solution to the original question to exist, applyCardBorders() would need to run not only when the user opens the print dialogue, but also any time they changed the paper size, margins, scale, etc. within the print dialogue. No such hook exists.

Even using max-width: 6in; doesn't work when the screen is narrower than 6 inches. It only works when the screen size at least as wide as 6 inches. In general, the drawn borders will render correctly in the print preview if the card on screen is already at its maximum width and that maximum width not wider than it would be in the paper. However, using width: 6in; would be better if you want a specific size.

Printing layouts are tricky, but if you know you will be printing to a specific size, you could do the following:

<div id="print-area">
  <div class="card">
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
  </div>
</div>
const printWidth = '10.5in';
const printArea = document.getElementById('print-area');
window.addEventListener('beforeprint', () => {
  printArea.style.width = printWidth;
  applyCardBorders();
});
window.addEventListener('afterprint', () => {
  printArea.style.removeProperty('width');
  applyCardBorders();
});

You could even make a dropdown for paper sizes on the screen and give the dropdown a class of screen-only:

@media print {
  .screen-only {
    display: none !important;
  }
}
Reasons:
  • Blacklisted phrase (1.5): any solution
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: redmoncoreyl