Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define a CSS class to set the printed page in landscape mode?

Tags:

css

I have created a CSS style sheet which can print an HTML page in landscape mode using the following @media rule:

   @media print{
      @page {size: landscape;}
    }

I do not want to print all HTML pages which load this style sheet in landscape mode. Ideally, I'd like to be able to specify a landscape class which would do this.

As the HTML is generated, I could always create a separate landscape.css file and append it to the header as needed, but I was hoping that there might be a cleaner way to do this with classes.

As a follow-up, I also tried the following with no luck:

@page rotated {
  size: landscape;
}
@media print{
  .rotate {
    page: rotated;
  }
}

I am probably just beating my head against a wall for a solution that only appears to work in webkit based browsers. The @page size: landscape setting does not appear to work in Firefox or (surprise, surprise) ie10.

like image 605
Alan Krause Avatar asked May 20 '13 17:05

Alan Krause


People also ask

How do you write a print page in CSS?

HTML, CSS and JavaScript You can use CSS to change the appearance of your web page when it's printed on a paper. You can specify one font for the screen version and another for the print version. You have seen @media rule in previous chapters. This rule allows you to specify different style for different media.


1 Answers

Unfortunately, we are currently unable to utilize page type selectors for media queries beyond the supplied :left, :right, :first, and :blank pseudo-classes.

https://www.w3.org/TR/css3-page/#page-selector-and-context

The W3C is however considering the addition of other page pseudo-classes for future levels of CSS [@page :nth(4) { ... } or @page (.class) { ... }]. I'm not sure why named pages were not able to work, but as of Jan 26, 2016, level 4 media queries (including the @page at-rule) may include ranges, negation, and custom media queries using scripting. Further, the size property is currently only supported in Chrome.

https://www.w3.org/TR/mediaqueries-4/

This is the closest I was able to get using just HTML and CSS, which applies landscape orientation to even-numbered pages. I know this isn't an exact solution, and it only works in Chrome.

<html>
    <head>
        <style>
            .landscape {
                page-break-before: always;
            }
            @page :left {
                size: landscape;
            }
        </style>
    </head>
    <body>
        <p>This is a normal paragraph.</p>
        <p class="landscape">This is in landscape form, following a page break.</p>
    </body>
</html>
like image 138
srbrills Avatar answered Oct 26 '22 04:10

srbrills