0

I am building a HTML page specifically for printing. I want to place text boxes (DIVs) on the printed report exactly where the customer wants them.

Challenge:

  • My HTML needs to print 2 pages.
  • Each page needs to contain a box one inch from the left and one inch from the top. The box should be 1 inch wide and 1 inch high.

Sounds easy, right?

I came up with the following HTML code, but it contains a problem. On page 2, the box is printed just a tiny bit higher than on page 1. You can spot the problem int the print preview. The problem appears in every browser I tried... so I can't even blame the browser!

Any ideas?

This is my attempt:

<!DOCTYPE html>
<html>
<head>
    <style>

        @page {
            margin: 0mm;
        }

        .box {
            position: absolute;
            left: 1in;
            top: 1in;
            width: 1in;
            height: 1in;
            background-color: gray;
            overflow:hidden;
        }

        .page {
            page-break-after: always;
            position: relative;
            height: 297mm;
            width:210mm;
        }
    </style>
</head>
<body>


<div class="page" id=page1">
    <div class="box">this box is placed properly.</div>
</div>

<div class="page" id=page2">
    <div class="box">this box is just a bit too high!</div>
</div>

</body>
user1691896
  • 107
  • 7

1 Answers1

0

There is default margin on body, in my browser it is 8px so you should change it to:

body {
    margin: 0px;
}

The top position is now the same, but my browser shown an extra page at the end, you can do some trick to get rid of it:

.page {
    border: 1px solid transparent;
}

See also: HTML default body margin, how to avoid extra blank page at end while printing?

Ben
  • 5,069
  • 4
  • 18
  • 26