- @page
- Syntax
- Descriptors
- Description
- Related properties
- Formal syntax
- page-properties
- margin at-rules
- page-margin properties
- Named pages
- Examples
- Using the size property to change the page orientation
- HTML
- CSS
- JavaScript
- Result
- @page pseudo-class examples
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Печать HTML страниц
- Подключение CSS
- Специальный CSS-файл:
- Правило @media print:
- Размер страницы
- Поля
- Удаление лишних стилей
- Размер шрифта
- Скрытие лишних элементов
- Показ элемента только при печати
- Печать фона background
- Разрывы страниц
- Отображение URL в ссылках
- Пример вставки URL:
- Вывод QR-кода при печати
- Запуск печати
@page
The @page at-rule is a CSS at-rule used to modify different aspects of a printed page property. It targets and modifies the page’s dimensions, page orientation, and margins. The @page at-rule can be used to target all pages in a print-out, or even specific ones using its various pseudo-classes.
Syntax
/* Targets all the pages */ @page size: 8.5in 9in; margin-top: 4in; > /* Targets all even-numbered pages */ @page :left margin-top: 4in; > /* Targets all odd-numbered pages */ @page :right size: 11in; margin-top: 4in; > /* Targets all selectors with `page: wide;` set */ @page wide size: a4 landscape; >
Descriptors
Specifies the orientation of the page. This does not affect the layout of the page; the rotation is applied after the layout in the output medium.
Specifies the target size and orientation of the page box’s containing block. In the general case, where one page box is rendered onto one page sheet, it also indicates the size of the destination page sheet.
Description
Note: This documentation lists out features yet to be implemented across UAs, but they are stated in the official documentation. At the time of this writing, the only CSS property shown to have visible on both the at-rule and its pseudo-classes is the margin property.
You can’t change all CSS properties with @page . You can only change the margin of the document. Attempts to change any other CSS properties will be ignored.
The @page at-rule can be accessed via the CSS object model interface CSSPageRule .
Note: The W3C is discussing how to handle viewport-related units, vh , vw , vmin , and vmax . Meanwhile do not use them within a @page at-rule.
Related properties
The @page at-rule, allows the user to assign a name to the rule, which is then called in a declaration using the page property.
Allows a selector to use a user defined named page
Formal syntax
@page =
@page ? < >
=
#
=
[ ? * ]!
=
‘:’ [ left | right | first | blank ]
and represents these pseudo-classes:
Note: The @page at-rule can only contain page-properties and margin at-rules, and the margin at-rules can only contain page-margin properties
page-properties
Feature | CSS properties |
---|---|
bidi properties | direction |
background properties | background-color |
background-image | |
background-repeat | |
background-attachment | |
background-position | |
background | |
border properties | border-top-width |
border-right-width | |
border-bottom-width | |
border-left-width | |
border-width | |
border-top-color | |
border-right-color | |
border-bottom-color | |
border-left-color | |
border-color | |
border-top-style | |
border-right-style | |
border-bottom-style | |
border-left-style | |
border-short-style | |
border-top | |
border-right | |
border-bottom | |
border-left | |
border | |
counter properties | counter-reset |
counter-increment | |
color | color |
font properties | font-family |
font-size | |
font-style | |
font-variant | |
font-weight | |
font | |
height properties | height |
min-height | |
max-height | |
line height | line-height |
margin properties | margin-top |
margin-right | |
margin-bottom | |
margin-left | |
margin | |
outline properties | outline-width |
outline-style | |
outline-color | |
outline | |
padding properties | padding-top |
padding-right | |
padding-bottom | |
padding-left | |
padding | |
quotes | quotes |
text properties | letter-spacing |
text-align | |
text-decoration | |
text-indent | |
text-transform | |
white-space | |
word-spacing | |
visibility | visibility |
width properties | width |
min-width | |
max-width |
margin at-rules
The margin at-rules are used inside of the @page at-rule. They each target a different section of the document printed page and make changes based on the properties or content set in the block of code:
@top-left targets the top-left of the document and applies the changes based on the page-margin-properties set.
Other margin-at rules include:
@top-left-corner < > @top-left < > @top-center < > @top-right < > @top-right-corner < > @bottom-left-corner < > @bottom-left < > @bottom-center < > @bottom-right < > @bottom-right-corner < > @left-top < > @left-middle < > @left-bottom < > @right-top < > @right-middle < > @right-bottom < >
page-margin properties
The page-margin properties are the set of CSS properties can be set in any individual margin at-rule. They include:
Feature | CSS properties |
---|---|
bidi properties | direction |
background properties | background-color |
background-image | |
background-repeat | |
background-attachment | |
background-position | |
background | |
border properties | border-top-width |
border-right-width | |
border-bottom-width | |
border-left-width | |
border-width | |
border-top-color | |
border-right-color | |
border-bottom-color | |
border-left-color | |
border-color | |
border-top-style | |
border-right-style | |
border-bottom-style | |
border-left-style | |
border-short-style | |
border-top | |
border-right | |
border-bottom | |
border-left | |
border | |
counter properties | counter-reset |
counter-increment | |
content | content |
color | color |
font properties | font-family |
font-size | |
font-style | |
font-variant | |
font-weight | |
font | |
height properties | height |
min-height | |
max-height | |
line height | line-height |
margin properties | margin-top |
margin-right | |
margin-bottom | |
margin-left | |
margin | |
outline properties | outline-width |
outline-style | |
outline-color | |
outline | |
padding properties | padding-top |
padding-right | |
padding-bottom | |
padding-left | |
padding | |
quotes | quotes |
text properties | letter-spacing |
text-align | |
text-decoration | |
text-indent | |
text-transform | |
white-space | |
word-spacing | |
vertical alignment | vertical-align |
visibility | visibility |
width properties | width |
min-width | |
max-width | |
z-index | z-index |
Named pages
Named pages enable performing per-page layout and adding page-breaks in a declarative manner when printing.
Named pages can be applied using the page property. This allows the user to create different page configurations for use in print layouts.
An example of this can be found on the page examples.
Examples
Using the size property to change the page orientation
This example shows how to split the s into individual pages in landscape format with each page having a 20% margin when printed.
HTML
button>Print Webpagebutton> article> section> h2>Headerh2> p> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Consequatur facilis vitae voluptatibus odio consequuntur optio placeat? Id, nam sequi aut in dolorem dolores, laudantium, quasi totam ipsam aliquam quibusdam velit. p> section> section> h2>Headerh2> p> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Consequatur facilis vitae voluptatibus odio consequuntur optio placeat? Id, nam sequi aut in dolorem dolores, laudantium, quasi totam ipsam aliquam quibusdam velit. p> section> section> h2>Headerh2> p> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Consequatur facilis vitae voluptatibus odio consequuntur optio placeat? Id, nam sequi aut in dolorem dolores, laudantium, quasi totam ipsam aliquam quibusdam velit. p> section> section> h2>Headerh2> p> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Consequatur facilis vitae voluptatibus odio consequuntur optio placeat? Id, nam sequi aut in dolorem dolores, laudantium, quasi totam ipsam aliquam quibusdam velit. p> section> section> h2>Headerh2> p> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Consequatur facilis vitae voluptatibus odio consequuntur optio placeat? Id, nam sequi aut in dolorem dolores, laudantium, quasi totam ipsam aliquam quibusdam velit. p> section> article>
CSS
@page size: landscape; margin: 20%; > body font-family: "Helvetica"; background-color: rgb(110 110 119); > article width: 100%; > section display: grid; background-color: white; border-radius: 0.6rem; margin-block-end: 1.5rem; justify-items: center; padding: 1rem; width: 50%; page-break-after: always; break-after: page; print-color-adjust: exact; -webkit-print-color-adjust: exact; > section page-break-after: always; break-after: page; > @media print button display: none; > >
JavaScript
const button = document.querySelector("button"); button.addEventListener("click", () => window.print(); >);
Result
Clicking the print button will launch a print dialog with the html sections split into individual pages.
@page pseudo-class examples
Please refer to the various pseudo-classes of @page for examples.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- The @page size descriptor
- The page property
- See the [META] CSS Paged Media Module Level 3 ticket in Bugzilla for tracking progress on the subject (page-based counters, etc.)
Found a content problem with this page?
This page was last modified on Jul 18, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Печать HTML страниц
Очень часто разработчики забывают про печатную версию сайта, поэтому можно встретить такой результат на бумаге:
Подключение CSS
Специальный CSS-файл:
Правило @media print:
Третий метод – отдельная страница или шаблон, свёрстанные чисто под печать (без @media print ), например так сделана печать писем в Яндекс.Почте. Такой метод существенно облегчает отладку.
Размер страницы
- при dpi=75, А4 имеет 877×620 px
- при dpi=150, А4 имеет 1754×1240 px
- при dpi=300, А4 имеет 3508×2480 px
Поля
В целях экономии бумаги лучше использовать минимальные поля – 10 мм по краям и 20 мм слева для возможности брушеровки.
Поля по ГОСТ Р 6.30-2003 (оформление документов):
По ГОСТ 7.32-2017 (научные работы, рефераты):
Удаление лишних стилей
Тени и другие эффекты дизайна лучше убрать, также следует установить черный цвет шрифта.
Размер шрифта
Если на сайте размер шрифтов указан в пикселях, то при печати размер будет больше чем на экране. Поэтому нужно выставить новые значения:
Скрытие лишних элементов
Т.к. на бумаге элементы навигации, баннеры, шапка, подвал, и другие элементы не несут какой либо пользы, то лучше их скрыть или оставить в них только самое важное.
Другой вариант скрытия не нужного контента – в HTML-коде, добавить к скрываемым элементам класс noprint .
Не стоить забывать о , обычно для сайтов с фиксированным размером ему задана ширина, отступы и центрирование, поэтому при печати возможна обрезка контента с правого края, такие стили стоит обнулить.
Показ элемента только при печати
@media screen < .element < display: none; >> @media print < .element < display: block; >>
Печать фона background
По умолчанию браузеры не печатают background у элементов, но его можно пустить на печать принудительно c помощью свойства -webkit-print-color-adjust: exact; и нового color-adjust: exact; .
Уточнение: свойство не будет работать если цвет фона и шрифта слабоконтрастные.
Разрывы страниц
В CSS доступно управление переносами, соответственно для списков и таблиц нужно запретить переносы:
Если требуется принудительно сделать перенос после элемента:
Отображение URL в ссылках
Печать ссылок бесполезна т.к. будет не известно, куда они ведут. Можно добавить приписку URL рядом с анкором (исключая якорные ссылки).
Пример вставки URL:
Вывод QR-кода при печати
Будет очень удобно если на печатаной странице будет QR-код с ссылкой на сайт. Сгенерировать код можно с помощью сервиса «Google QR Codes» и вставить его с помощью JQuery.
Запуск печати
В JS, печать запускается методом window.print() . Возможны следующие варианты: Запуск печати по клику на ссылку:
Следующий вариант – пользователь переходит на следующую страницу, где сразу начинается печать, после пользователь возвращается на исходную.
И последний вариант – печать происходит в отдельной вкладке браузера, после печати она автоматически закрывается.