Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

css - HTML div with A4 dimensions is larger than A4

I set the size of a parent div to A4 (size="21cm 29.7cm"). However, in Chrome print preview, with A4 and no margins, the HTML page won't fit on A4. I have to scale it to 80%.

Is there something in my HTML causing this? I expected the size="21cm 29.7cm" to force the page to be A4.

UPDATE I found this:

CSS to set A4 paper size

And tried the below CSS, but not working:

@page {
  size: A4;
  margin: 0;
}
@media print {
  html, body {
    width: 210mm;
    height: 297mm;
  }
}

HTML:

<!Doctype>
<html>
<head>
  <style>
    .background
    {
      position: relative;
      top: 0;
      left: 0;
    }
    .text
    {
      position: absolute;
      top: 0px;
      left: 0px;
      width: 1449px;
      height: 2050px;
    }
  </style>
</head>
<body>
  <div style="position: relative; left: 0; top: 0;" size="21cm 29.7cm">
    <img src='page0022.jpg' class="background"/>
    <img src='0022.svg' class="text"/>
  </div>
</body>
</html>
question from:https://stackoverflow.com/questions/65862676/html-div-with-a4-dimensions-is-larger-than-a4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Read about size: https://developer.mozilla.org/en-US/docs/Web/CSS/@page/size

Add these code to your HTML file:

<div class="page">...</div>

Add these code to your CSS file

@page {
    size: 21cm 29.7cm;
    margin: 30mm 45mm 30mm 45mm;
     /* change the margins as you want them to be. */
}

@media print {
    body{
        width: 21cm;
        height: 29.7cm;
        margin: 30mm 45mm 30mm 45mm; 
        /* change the margins as you want them to be. */
   } 
}

In case you think you really need pixels (you should actually avoid using pixels), you will have to take care of choosing the correct DPI for printing:

  • 72 dpi (web) = 595 X 842 pixels
  • 300 dpi (print) = 2480 X 3508 pixels
  • 600 dpi (high quality print) = 4960 X 7016 pixels

Yet, I would avoid the hassle and simply use cm (centimetres) or mm (millimetres) for sizing as that avoids rendering glitches that can arise depending on which client you use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...