CSS Media Queries for Print Paper Size

CSS to set A4 paper size

I looked into this a bit more and the actual problem seems to be with assigning initial to page width under the print media rule. It seems like in Chrome width: initial on the .page element results in scaling of the page content if no specific length value is defined for width on any of the parent elements (width: initial in this case resolves to width: auto ... but actually any value smaller than the size defined under the @page rule causes the same issue).

So not only the content is now too long for the page (by about 2cm), but also the page padding will be slightly more than the initial 2cm and so on (it seems to render the contents under width: auto to the width of ~196mm and then scale the whole content up to the width of 210mm ~ but strangely exactly the same scaling factor is applied to contents with any width smaller than 210mm).

To fix this problem you can simply in the print media rule assign the A4 paper width and hight to html, body or directly to .page and in this case avoid the initial keyword.

DEMO

@page {
size: A4;
margin: 0;
}
@media print {
html, body {
width: 210mm;
height: 297mm;
}
/* ... the rest of the rules ... */
}

This seems to keep everything else the way it is in your original CSS and fix the problem in Chrome (tested in different versions of Chrome under Windows, OS X and Ubuntu).

Detect Printer's Page Size in CSS or JavaScript

The following media query has been working reliably for me with receipt printers:

@media print and (max-width: 10cm) { }

On a somewhat related note: Unfortunately, this isn't working (customers have to manually set margins to none or minimal)

@page { margin: 0; }

Happy coding

Change CSS if A5 size paper is chosen when printing?

you could try the following media queries although I'm not sure how wide spread the support is:

/* style sheet for "A4" printing */
@media print and (width: 21cm) and (height: 29.7cm) {
@page {
margin: 3cm;
}
}

/* style sheet for "letter" printing */
@media print and (width: 8.5in) and (height: 11in) {
@page {
margin: 1in;
}
}

function paperSelect(){

var elems = document.body.getElementsByTagName("*");

if (event.target.id == 'a3'){
for(let i = 0; i < elems.length; i++){
elems[i].classList.add("mystyle");
}
}else{
for(let i = 0; i < elems.length; i++){
elems[i].classList.remove("mystyle");
}
}

}
li{
display:block;
}

li.mystyle{
display:inline;
}
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
A4<input id='a4' type='radio' name='print' checked onchange='paperSelect()'>or A3
<input id='a3' type='radio' name='print' onchange='paperSelect()'>


Related Topics



Leave a reply



Submit