The fancyhdr package
Defines the header and footer of a page in three parts each (left, centre, right) with \fancyhead and \fancyfoot.
Loading the package
\usepackage{fancyhdr}The standard classes offer only the fixed page styles plain, headings and empty. fancyhdr adds the page style fancy, whose header and footer you fill yourself: page number, section title, a logo or fixed text, with an optional rule below the header and above the footer.
The letters in the optional argument select the position: L, C, R for left, centre and right, combined with E and O for even and odd pages in a two-sided document. \leftmark and \rightmark hold the current headings: in article the section and the subsection, in report and book the chapter and the section.
Main commands
\pagestyle{fancy} | Switches the document to the page style fancy. |
\fancyhf{} | Clears all header and footer fields, so the defaults disappear. |
\fancyhead[L]{text} | Sets the left part of the header; [LE,RO] means left on even and right on odd pages. |
\fancyfoot[C]{\thepage} | Puts the page number in the centre of the footer. |
\renewcommand{\headrulewidth}{0.4pt} | Thickness of the rule below the header; 0pt removes it. \footrulewidth does the same for the footer. |
\fancypagestyle{plain}{...} | Redefines the style plain, which the first page of a chapter and the title page use. |
\leftmark, \rightmark | The current higher-level and lower-level heading, for use in a header field. |
Complete example
\documentclass{article}
\usepackage{fancyhdr}
\setlength{\headheight}{14pt}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[L]{\leftmark}
\fancyhead[R]{Project report}
\fancyfoot[C]{\thepage}
\renewcommand{\headrulewidth}{0.4pt}
\begin{document}
\section{Introduction}
The header shows the section title on the left and a fixed text on the right.
The page number sits in the centre of the footer.
\end{document}Compiled with pdfLaTeX from TeX Live 2023.
Pitfalls
- The warning
\headheight is too smallnames the height the header needs. Set it with\setlength{\headheight}{14pt}or with theheadheightoption ofgeometry. - Pages that start a chapter, and the page with
\maketitle, use the styleplainand ignore yourfancysettings. Redefine it with\fancypagestyle{plain}{...}. - KOMA-Script classes print a warning when
fancyhdris loaded and recommendscrlayer-scrpageinstead. \leftmarkand\rightmarkcome in capitals.\nouppercase{\leftmark}prints the heading as written.
Related pages
- How-to Headers and footers in LaTeX
- How-to Page numbers in LaTeX
- Package
scrlayer-scrpage - Package
geometry