CSS @page explained

CSS @page detailed explanation

CSS @page detailed explanation

In CSS, the @page rule is used to define page characteristics for printed documents, such as page size, headers, and footers. Using the @page rule, we can control the layout and style of printed pages, ensuring the printed result meets our needs.

@page Rule Syntax

@page rules can be defined directly in CSS files or embedded in HTML documents using the <style> tag. Their syntax is as follows:


@page {
/* Define page properties */
}

Page properties that can be set in the @page rule include:

  • size: Used to set the page size. You can set it to a fixed value (such as A4) or a custom size (such as 100px or 200px).
  • margin: Used to set the page margins. You can set it to a fixed value (such as 10mm) or set the top, right, bottom, and left margins separately.
  • marks: Sets whether to display the header and footer markup.
  • bleed: Sets the page content to extend to the edge of the page to avoid white margins.
  • @top-left, @top-center, @top-right, @bottom-left, @bottom-center, @bottom-right: Sets the header and footer content.

Sample Code

The following is a simple @page rule example that sets the page size to A4, margins to 2cm, and displays the header and footer markup:

@page {
size: A4;
margin: 2cm;
marks: cross; 
} 

@page Rule Example

Setting Page Size and Margins

We can use the @page rule to set the size and margins of a printed page. Here’s an example setting an A4 size and 1cm margins:

@page {
size: A4;
margin: 1cm;
} 

Displaying Headers and Footers

Using the @page rule, we can set the header and footer marks to display. Here’s an example setting the header and footer marks to display:

@page {
marks: cross; 
} 

Define header and footer content

In addition to displaying header and footer tags, we can also use the @page rule to define specific header and footer content. The following is an example that displays “Page X” centered at the top of the page and the date at the bottom of the page:

@page { 
@top-center { 
content: "Page " counter(page); 
} 
@bottom-center { 
content: "Date: " attr(data-date); 
} 
} 

In this example, @top-center defines the content to be displayed at the top center of the page, and uses the content attribute to set the displayed content to “Page X.” X”, where counter(page) is used to display the page number. @bottom-center defines the content to be displayed at the bottom center of the page, and attr(data-date) is used to display the value of the data-date attribute, which is usually used to display date information.

Conclusion

The @page rule allows for more flexible control of page layout and style when printing documents, allowing for customized printing results. In practice, we can customize page size, margins, header and footer content, and other attributes to meet specific printing requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *