Nicolas Cadilhac
Nicolas Cadilhac

Reputation: 4745

Chrome, print and percent divs

I'm designing a simple html page whose sole intent is to be printed. I don't care how it looks on screen but it must print on a SINGLE page (A4 or letter) and from any browser. Therefore I need to use divs sized only with percents.

The problem with the following skeleton code is that on Chrome print preview, the 2 words are displayed both on the first line, contrarily to what is displayed in the web page. I don't get this issue in FF and IE.

<!DOCTYPE html>

<html>

<head>
    <style type="text/css">
    html, body, div, p, span { margin:0px;padding:0px; }
    html, body { width:100%;height:100%;min-height:100%;}
    </style>
</head>

<body>

    <div style="height:70%;">
      first
    </div>

    <div style="height:30%;">
      second
    </div>

</body>
</html>

Upvotes: 0

Views: 3157

Answers (2)

Shridhar
Shridhar

Reputation: 166

Use @media print, check css media types and how to use it. For example here is written sample, you can remove borders added just to test.

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
    @media screen {
    html, body, div, p, span { margin:0px;padding:0px; }
    html, body { width:100%;height:100%;}
    div.first {height:70%; width:100%;   }
    div.second {height:30%; width:100%; }
    }
    @media print {
    html, body, div, p, span { margin:0px;padding:0px; }
    html, body { width:100%;height:100%;}
    div.first {height:70%; width:100%; border:1px solid red; display:block;   position:fixed; top:0; left:0;  }
    div.second {height:30%; width:100%; border:1px solid blue; display:block; position:fixed; bottom:0; left:0; }

    }
    </style>
</head>
<body>
    <div class="first">
     first
    </div>
    <div class="second">
      second
    </div>
</body>
</html>

Upvotes: 0

Michael
Michael

Reputation: 7092

Letter is the smallest size of the so to say "standard" paper types. It is a little wider than A4 though. So why not constrain yourself to the height of Letter and the width of A4? You'll want to incorporate some margin space anyways, which should account for a a good portion of width differences.

To that end, what about switching from percentages to actual inches or even millimeters (more precise). CSS does support these units.

For example calculate your 70% of page size in millimeters for the tallest paper size you support and the smallest paper size you support. Lets use Letter and A4. So 70% of 279mm (Letter) = 195.3 rounded down (safer) to 195. So put min-height: 195mm; Then for A4 70% of 297 = 207.9 rounded down = 207 so max-height: 207mm;

Calculating for 30%...

min-height: 83mm;
max-height: 89mm;

Seems sound to me, not sure why it wouldn't work?

Upvotes: 1

Related Questions