Home >Web Front-end >CSS Tutorial >How Can I Remove Headers and Footers When Using `window.print()`?
Eliminating Header and Footer from 'window.print()'
When utilizing window.print() to print a page, you may encounter an issue with headers and footers displaying page details like the title, path, page number, and date. These can be distracting and interfere with the desired print output.
To address this issue, a solution has been discovered that is effective in the Chrome browser (as of October 2022, it also works in Firefox). By employing the following stylesheet, you can suppress the automatic header and footer that Chrome generates:
@page { margin: 0; }
This stylesheet sets the page margins to zero, causing the content to extend to the edges of the page. As a result, the header and footer, which are normally displayed outside the printable area, are effectively hidden.
To prevent the content from overflowing the page's boundaries, it is recommended to set margins or paddings to the page element:
@media print { @page { margin: 0; } body { margin: 1.6cm; } }
In this example, a 1.6cm margin is applied to the top and bottom of the page, ensuring that the content remains within the printable area.
It is important to note that if the content is too large and requires multiple pages, this solution may not produce an optimal result. Only the first page will have a top margin, and only the last page will have a bottom margin. Intermediate pages will have no margins, which may not be desirable.
If you need to support browsers that do not handle this stylesheet effectively, alternative solutions such as creating and printing a PDF on the fly may be necessary, although these methods can be complex and time-consuming to implement.
The above is the detailed content of How Can I Remove Headers and Footers When Using `window.print()`?. For more information, please follow other related articles on the PHP Chinese website!