CSS - Pseudo-class :first



The CSS pseudo-class selector :first selects the first page of a printed document. It is used with the @page at-rule.

All CSS properties can not be changed using the :first pseudo-class. The properties that can be changed are margins, orphans, widows, and page breaks of the document. Also, only absolute-length units can be used for margins, while using this pseudo-class. All the other properties will be ignored.

Orphan is a CSS property that sets the minimum number of lines in a block container, that must be shown at the bottom of a page.

Widow is a CSS property that sets the minimum number of lines in a block container, that must be shown at the top of a page.

Syntax

:first {
   /* ... */ 
}

CSS :first Example

Following example demonstrates use of :first pseudo-class. Here we see:

  • A document is created with three pages, as we have used page-break-after: always on p element.

  • the pseudo-class :first is applied, which will result in the styling of margin set on first page only. The text will appear at the bottom right corner of the page. Rest two pages show the text on its default location.

<html>
<head>
<style>
   @page :first {
      margin-left: 80%;
      margin-top: 80%;
   }

   p {
      page-break-after: always;
      background-color: lightblue;
      padding: 5px;
   }
</style>
</head>
<body>
   <p>Page One</p>
   <p>Page Two</p>
   <p>Page Three</p>
   <button>Print Me</button>
   <script>
      document.querySelector("button").addEventListener("click", () => {
      window.print();
      });
   </script>
</body>
</html>
Advertisements