A page is a stack of bands, and only one is your text
Above \textheight there are three lengths and one that TeX itself adds. From the top of the paper: an untyped 1 inch (a TeX primitive offset, which is why "top margin" in a LaTeX manual never means what you measured), then \voffset plus \topmargin down to the top of the header box, then \headheight — the declared height of that box — then \headsep, the gap between the rule and the first text line. Below the text comes \skip\footins and any footnote insertions, then \footskip down to the baseline of the first footer line, not the top of the footer.
The two numbers most often wrong are \headheight and \footskip. \headheight is not "how much space I would like": it is a declaration the output routine trusts. If the header content is taller than the declared height, TeX does not resize the page — it lets the header overlap the text and tells you so in the log. \footskip being too small pushes the footer into the footnote area, and in a document with many footnotes that is where the collision appears.
Do all of it with geometry and let it keep \textheight consistent: \usepackage[a4paper,top=2.5cm,bottom=2.8cm,headheight=15pt,headsep=14pt,footskip=26pt]{geometry}. Setting these by hand with \setlength after the class has computed the page is possible and is how the older classes were tuned, but it requires you to fix \textheight, \vsize and the top margin in the same edit, which is exactly the arithmetic geometry exists to do.
V = \underbrace{h_{\text{top}}}_{\text{above the header}} + \underbrace{h}_{\text{headheight}} + s_{\text{head}} + \underbrace{T}_{\text{textheight}} + f_{\text{note}} + s_{\text{foot}}
The style model: pagestyle versus thispagestyle
LaTeX keeps two pieces of state for furniture. \pagestyle{X} sets the style for every page from now on; \thispagestyle{Y} overrides it for the current page only, and is forgotten when that page ships out. The four built-in styles are empty (nothing), plain (page number centred in the footer — the default of the standard classes), headings (two rules-free lines of running heads built from marks) and myheadings (the same shape, fed by your own \markboth).
The conflict this creates is the single most-asked question about first pages. Commands that begin a unit issue their own \thispagestyle: \maketitle uses plain, \chapter uses plain, \part and \tableofcontents do the same, and \cleardoublepage sets empty on the blank verso it may insert. So \thispagestyle{empty} must be written after \maketitle, not before it, or the later call wins; and to suppress the folio on the first page of every chapter you do not fight the per-page call — you redefine the style it names, which is what \fancypagestyle{plain}{...} is for.
A hand-written title page inside titlepage has the same rule: put \thispagestyle{empty} immediately after \begin{titlepage}, because the environment ends by shipping out the page and the furniture is chosen at that moment, from the last call it saw.
The headings style is worth using even before fancyhdr, because it shows what a running head is made of: \leftmark on even pages, \rightmark on odd, and nothing but marks. That is the whole mechanism the next sections develop.
fancyhdr: six slots, and the two- and three-paragraph models
fancyhdr replaces the header and the footer each with a row of three boxes, giving six slots: \fancyhead[L], \fancyhead[C], \fancyhead[R] and \fancyfoot[L], [C], [R]. Start every setup with \fancyhf{}, which clears all six; without it you inherit whatever the previous definition left. The row is laid out as a single \hbox, which is why an empty centre slot changes nothing and why an over-wide left slot pushes the centre one off-axis — the model is "three paragraphs side by side", not "three independent boxes you can position freely".
For a two-sided document each slot is doubled, and the selector argument controls which page gets what: E even, O odd, L lefthand page, R righthand page, C both. \fancyhead[LE,RO]{\thepage} is the classic outside folio; \fancyhead[RE]{\leftmark}\fancyhead[LO]{\rightmark} is the classic mirrored running head, with chapter on the verso and section on the recto. Do not write \fancyhead[L] and expect it to mean "left page" — it means "left slot", and that distinction is where most mirrored-header debugging happens.
Three properties of the implementation matter in ordinary documents. An empty slot is still a box: fancyhdr fills it with a \strut-equivalent so the row has height, which is why "no header content" still needs a non-zero \headheight. The rule under the header is \headrule, drawn to \headwidth, not to \textwidth; its thickness is \headrulewidth, and setting it to 0pt removes it — with \renewcommand{\footrulewidth}{0.4pt} giving you the matching rule above the footer. And \headwidth can be extended into the margins with \fancyheadoffset, the usual way to make the rule span the full paper width for a header that reaches into the margin box.
For colour, do not wrap the rule in \textcolor; redefine the rule itself, since it is an \hbox to\headwidth{\leaders\hrule ...}: \renewcommand{\headrule}{\hbox to\headwidth{\color{accent}\leaders\hrule height \headrulewidth\hfill}}. Same trick for a double rule, with two \hrules at different heights inside the box.
w_{\text{rule}} = \text{headwidth} = \text{textwidth} + l_{\text{offset}} + r_{\text{offset}}
\documentclass[11pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
% headheight must be big enough for what the header holds; geometry then
% keeps \textheight consistent with the rest of the page.
\usepackage[a4paper,top=2.5cm,bottom=2.8cm,left=3cm,right=3cm,
headheight=15pt,headsep=14pt,footskip=26pt]{geometry}
\usepackage{xcolor}
\usepackage{lastpage} % \pageref{LastPage} for "of 12"
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{} % clear all six slots first
\fancyhead[L]{\small\nouppercase{\leftmark}}
\fancyhead[R]{\small\itshape A. Student}
\fancyfoot[C]{\small\thepage\ of \pageref{LastPage}}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0pt}
\renewcommand{\headrule}{%
\hbox to\headwidth{\color{blue!60!black}\leaders\hrule height \headrulewidth\hfill}}
\setlength{\headwidth}{\textwidth}
\title{Headers and footers, concretely}
\author{A. Student}
\begin{document}
\maketitle % \maketitle issues its own \thispagestyle{plain}
\thispagestyle{empty} % so the override goes AFTER it, never before
\section{Definitions}
Because the section title is put into the left mark by the class, the header of
this page reads \emph{Definitions}. A running head has to be produced from a
mark, not from the heading command itself: the header is typeset when the page
is shipped out, long after the heading was seen.
\begin{equation}
\label{eq:cauchy}
\int_{\gamma} f(z)\,dz = 0
\end{equation}
Equation \eqref{eq:cauchy} is unaffected by any of the above, which is the point:
page furniture and content are laid out by different mechanisms.
\section{Further remarks}
A two-line header needs a larger \verb|headheight|: ask geometry for
\verb|headheight=26pt| instead of ignoring the warning, and recompile, because
the taller band moves every page break below it.
\end{document}
The headheight warning and what to do about it
The message reads, verbatim enough: Package fancyhdr Warning: \headheight is too small (12.0 pt), followed by the dimensions of the header it measured and a suggestion. It is not cosmetic. fancyhdr computes the natural height of the header box, compares it with the declared \headheight, and if the declaration is smaller it cannot shrink the header — the page is already cut, so the box overlaps the first text line and the log is the only evidence.
Fix it at the source of the declaration, in the order that matches how you set the page: with geometry, add headheight=15pt (or the value fancyhdr printed); with plain \setlength, write \setlength{\headheight}{15pt} in the preamble and remember that changing it does not automatically recompute \textheight, so text will run lower on the page. Then re-run: because the header height changed \textheight-adjacent material, page breaks move, which can change the marks, which can change header widths, which can trigger the warning again with a new number.
The causes are always one of four. A header line containing \frac or any display-ish material, which is far taller than a text line — set the maths small (\scriptstyle) or in \mbox{} with \footnotesize. A two-line header, which needs roughly double the height and is why a thesis with a stacked header often declares 26pt or more. A header that includes an \includegraphics logo. And a document whose class sets \headheight very small at 12pt, which the standard classes do.
Related and equally real: fancyhdr also warns about headwidth ("\headwidth... overwritten") when a package such as geometry changes the text block after fancyhdr read it, and about footerrule-style collisions when the footer plus \footskip runs off the page. Both are cured by loading geometry first with all its values settled, then fancyhdr, then never touching either length again by hand.
Marks: how a header knows where you are
A header cannot ask what section it is in, because by the time the header is typeset the sectioning command is long gone and the page has been cut by the output routine. The mechanism is a mark: \markboth{left text}{right text} drops a note into the vertical list at the point it is called, and the output routine reads the notes found on the page being shipped. The standard classes call it for you — \section issues \sectionmark{...}, which is \markboth{...}{...} — and that is where the running head text comes from.
The retrieval half is where the confusion lives, and the kernel documentation is precise about it: \leftmark returns the last left mark on the page, while \rightmark returns the first right mark. That asymmetry is deliberate — chapter on the verso as you turn it, section on the recto as you enter it — and it is the reason the header can look "one section behind" or "one section ahead" depending on which slot you used. There are also \topmark (the mark current at the top of the page), \firstmark and \botmark.
Since the 2020 marking update LaTeX keeps first and last values of each mark class separately, which gives you the missing combinations. The classes used by \markboth/\markright are named 2e-left, 2e-right and 2e-right-nonempty, and the generic retrievers are \TopMark{class}, \FirstMark{class} and \LastMark{class} — so \LastMark{2e-right} gives the last section on the page, which is what a "you are reading X" header wants. Your own marks come from \NewMarkClass{status} plus \InsertMark{status}{text}, and one important caveat in the manual: mark retrieval is meaningful only inside the output routine, and in a one-sided document the standard classes set right marks only, so \leftmark can be empty by design.
The two practical problems marks create are fixable in one line each. Uppercase: the standard classes put \MakeUppercase into the mark, and fancyhdr supplies \nouppercase to undo it in the slot, which is why the idiom is \fancyhead[RE]{\nouppercase{\leftmark}}. Accented and maths-bearing titles: the mark holds the typeset form, so a section title with \texorpdfstring or a \footnote in it needs the short optional argument — \section[Plain form]{Pretty form} — or the header will contain furniture you did not want.
\text{leftmark} = \text{last left mark on the page}, \qquad \text{rightmark} = \text{first right mark on the page}
\documentclass[11pt,a4paper]{report}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage[a4paper,margin=2.5cm,headheight=26pt,headsep=16pt]{geometry}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[L]{%
\begin{minipage}[t]{.55\headwidth}\raggedright\footnotesize
\firstleftmark\\[1pt]
\footnotesize\itshape second line of the header, from a mark of its own
\end{minipage}%
}%
\fancyhead[R]{\footnotesize\thepage}
\renewcommand{\headrulewidth}{0.4pt}
\makeatletter
% Two-sided behaviour of \markboth: left part -> even pages, right -> odd.
% \leftmark reads the LAST left mark of the page, \rightmark the FIRST right mark.
\newcommand{\firstleftmark}{\FirstMark{2e-left}}
\makeatother
\begin{document}
\chapter{Marked material}\label{ch:one}
\section*{A section that is not numbered}
% Unnumbered headings set no mark, so the running head must be written by hand:
\markboth{Appendix: unnumbered material}{}
\addcontentsline{toc}{section}{Unnumbered material}
The header on the following pages now reads from the mark we set manually.
\section{Numbered from here}
\subsection{Deeper}
Because \verb|\rightmark| is the \emph{first} right mark on the page, a page
that starts with a new section shows that section in the header even when the
rest of the page belongs to the next one - the asymmetry behind the
"my header is one heading behind" complaint.
\begin{equation}
\label{eq:star}
\sum_{d\mid n} \varphi(d) = n
\end{equation}
Equation \eqref{eq:star} has nothing to do with page furniture, but its number
comes from the same two-pass mechanism, which is why adding a header line that
changes \verb|\headheight| can move it to another page.
\end{document}
Two-sided documents: mirroring, blank pages and folio placement
A twoside document is not the same page mirrored: the margins themselves swap, which is what geometry's inner=/outer= express, and the header follows. In the standard classes, book is two-sided by default while article is not, so the same header code behaves differently in the two templates — the most common cause of "it worked in my article and broke in my thesis".
Chapter openings are the other structural difference. With openright (the book default), \chapter runs \cleardoublepage, and if that leaves the chapter starting on a verso, an empty page is inserted — with \thispagestyle{empty} already applied, so it carries no folio. That is correct for a printed book and looks like a bug in a PDF review, and openany is the switch that removes it. Note also that a blank page inserted this way still consumes a page number, so the count and the printed folio disagree if you set numbering by hand.
Placement conventions worth following: the folio goes at the outer top or outer bottom in a monograph, never centred on both facing pages of a two-sided print (a centred folio drifts into the gutter). Running heads use chapter on the verso and section on the recto, in small caps or italic, and never both on one page. If you print at all, ask your press whether it counts page 1 as a recto; a document whose folio appears on the wrong side is nearly always off by one blank page at the front.
Finally, the two-sided page number question has a correct answer that is not arithmetic on \thepage: what matters is the physical page index, and the robust way to ask about it is the oddpage package's \checkoddpage plus \ifoddpage, which compares positions rather than printed numbers and needs two passes. Never test parity by looking at \value{page}: with roman front matter and an \includeonly build, the printed number and the physical page disagree.
\documentclass[12pt,a4paper,twoside]{book}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage[margin=2.6cm,marginparwidth=2.2cm,headheight=16pt]{geometry}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
% E = even pages, O = odd pages; L/R = left/right slot of that page.
\fancyhead[LE,RO]{\small\thepage} % folio outside
\fancyhead[RE]{\small\nouppercase{\leftmark}} % chapter, verso
\fancyhead[LO]{\small\nouppercase{\rightmark}} % section, recto
\fancyfoot[C]{\small\itshape Draft of \today}
\renewcommand{\headrulewidth}{0.4pt}
\fancyheadoffset[L]{0pt} % keep the rule exactly at \textwidth
% The style used by \chapter, \part and the TOC: they call \thispagestyle{plain},
% so redefining plain is how you decorate first pages without touching every call.
\fancypagestyle{plain}{%
\fancyhf{}%
\fancyfoot[C]{\small\thepage}%
\renewcommand{\headrulewidth}{0pt}%
}
\begin{document}
\frontmatter % roman page numbers, and it resets to i
\title{A Thesis}
\author{A. Candidate}
\date{}
\maketitle
\thispagestyle{empty}
\tableofcontents % own \thispagestyle{plain}
\listoffigures
\mainmatter % arabic again, restarting at 1
\chapter{Rings}
A chapter opens on a recto here and its first page uses the plain style redefined
above; later pages use the fancy style, and \verb|\leftmark| carries the chapter
title on the even pages.
\section{Modules}
\verb|\rightmark| carries the section title on the odd pages. A section that
begins at the very top of a page is the classic reason a running head appears
one section behind, because marks are resolved by the output routine for the
page as a whole.
\cleardoublepage % \thispagestyle{empty} on the blank verso
\chapter{Fields}
Both marks are set with \verb|\markboth| by the class: the book class issues
\verb|\chaptermark| and \verb|\sectionmark|, so the header text is the title
\emph{as typeset}, uppercase and all, unless \verb|\nouppercase| intercepts it.
\end{document}
Page numbering, front matter and the folio you do not want
Page numbers are a counter, and \pagenumbering{style} both changes its representation and resets it to 1 — which is why \frontmatter and \mainmatter in the book-family classes are not decoration: the first switches to roman, the second switches back to arabic and restarts. Reproduce it by hand in an article with \pagenumbering{roman}, then \clearpage, then \pagenumbering{arabic}. Doing it with \setcounter{page}{1} and a redefined \thepage instead is the way duplicate PDF destinations are born.
Suppressing the folio on the title page is a two-line job — \pagestyle{empty} before \maketitle if you want it off for the whole front matter, or \thispagestyle{empty} after \maketitle for just that page — and the ordering is the entire difficulty. A more robust variant for a document whose first page must be bare and whose numbering must still start at 1 on the next page is to set the counter explicitly after the title: \setcounter{page}{0} before \maketitle, so the following page is 1.
To print "3 of 12" you need the last page, and that is not known in one pass: the lastpage package provides \pageref{LastPage} and converges in two runs, and the zref-useri-based zref-lastpage is the variant that survives \includeonly builds and multi-scope documents. Both are marks of the same kind as everything else in this lesson: a value that only the previous pass can supply.
Restarts and offsets: \addtocounter{page}{-1} is the honest way to compensate for a page that must not be counted (a full-page figure, for instance), and it works but desynchronises printed from physical numbering, so links and reviewer comments land one page off. The alternative — \thispagestyle{empty} plus leaving the counter alone — keeps the physical numbering intact and prints no folio, which is nearly always what an examiner expects.
Recipes, and the things that go wrong with them
Commons: \pagestyle{fancy}\fancyhf{}\fancyhead[R]{\small\thepage}\fancyhead[L]{\small\nouppercase{\leftmark}}, with headheight=15pt in the geometry options. No header rule: \renewcommand{\headrulewidth}{0pt} — not \headrule{}, and not deleting \headheight. Chapter title on the left, section on the right, folio outside: the three \fancyhead[LE,RO]/[RE]/[LO] lines from the slot section. Different first page of each chapter: redefine the plain style with \fancypagestyle rather than adding \thispagestyle calls after every \chapter.
The failure that surprises most: nothing appears at all. Causes, in order of likelihood — \pagestyle{fancy} never issued, or issued before \usepackage{fancyhdr}; a \thispagestyle{plain} from \chapter/\maketitle/\tableofcontents overriding it on exactly the page you are looking at; the content living in a slot for the wrong page selector (writing \fancyhead[L] in a two-sided document fills the left slot of every page, which the mirrored layout then hides); or the whole header being there but overlapping the text because \headheight is 0 and the box was discarded.
Second: the header shows the wrong heading. That is marks, not furniture — read \leftmark and \rightmark with the first/last asymmetry in mind, set the mark yourself with \markboth{}{} after an unnumbered heading, and remember that a chapter-opening page uses plain and therefore shows no header however correct the mark is.
Third: the header is a mess of warnings about fragile commands. A \footnote, a \marginpar or a display in a header is a page insertion inside the output routine, which is illegal; \marginpar in a header fails outright, and a header containing \ref needs two passes and is a legitimate use of \mbox{} to keep it on one line. And if you need real control over chapter-page furniture, titlesec offers its own page-style interface (\newpagestyle) — set \pagestyleset{fancyhdr} first, so that the vocabulary you already learned stays the vocabulary you use.
h_{\text{measured}} > \text{headheight} \;\Longrightarrow\; \text{warning, and the header eats into the text}
Lesson cheat sheet
One key line of code from each section — jump to it or copy it straight from here.
V = \underbrace{h_{\text{top}}}_{\text{above the header}} + \underbrace{h}_{\text{headheight}} + s_{\text{head}} + \underbrace{T}_{\text{textheight}} + f_{\text{note}} + s_{\text{foot}}
\documentclass[11pt,a4paper]{article}
\documentclass[11pt,a4paper]{report}
\documentclass[12pt,a4paper,twoside]{book}
h_{\text{measured}} > \text{headheight} \;\Longrightarrow\; \text{warning, and the header eats into the text}
Common mistakes
- Writing
\thispagestyle{empty}before\maketitleor before\chapter{...}. Those commands issue their own\thispagestyle{plain}, which wins because it comes later. Put the override after them, or redefineplainwith\fancypagestyle. - Ignoring the
\headheightis too small warning. The header box is not shrunk and the page is not re-cut — the content simply overlaps the first text line, and the log is the only place that says so. - Setting
\headheightwith\setlengthand expecting the text block to move with it. Recompute the page withgeometry, or accept that\textheightis now wrong for the paper. - Using
\fancyhead[L]{...}in a two-sided book and calling the result "left page".Lselects the left slot; the page selectors areE,O,Lefthand andRighthand, as in\fancyhead[LE,RO]. - Expecting
\leftmarkto behave in a one-sidedarticle: the standard classes only maintain right marks on one side, and\leftmarkis the last left mark while\rightmarkis the first right mark of the page. - Restarting page numbers with
\setcounter{page}{1}instead of\pagenumbering{arabic}. Two pages then read "1", the destinations collide, and hyperref reports duplicate page names. - Putting a
\marginpar, a\footnoteor a display equation in a header. Page insertions are not allowed inside the output routine, so either nothing appears or the run stops.
Questions about this lesson
How do I put the page number in the top right corner in LaTeX?
\pagestyle{fancy}, \fancyhf{} to clear the slots, then \fancyhead[R]{\thepage} — or \fancyhead[LE,RO]{\thepage} for the outer corner of a two-sided document. Declare headheight in your geometry options, otherwise fancyhdr warns and the header overlaps the first line of text.Why is there no header on the first page of my chapter?
\chapter calls \thispagestyle{plain}, and plain is a different style from fancy. Either put \thispagestyle{fancy} right after the \chapter command for a one-off case, or redefine the style with \fancypagestyle{plain}{...} so that every chapter opening, table of contents and list of figures uses the furniture you want.What does the fancyhdr headheight warning mean?
\headheight the class declared. TeX cannot grow the band without re-cutting the page, so the header spills over the first text line. Set headheight= in the geometry options to the value the warning suggests, then recompile: the change shifts page breaks and can reveal a second, larger requirement.How do I show the current section name in the header?
\rightmark on the odd pages and \leftmark on the even ones, wrapped in \nouppercase if the class uppercased it. Remember the asymmetry documented in the kernel — \leftmark is the last left mark on the page while \rightmark is the first right mark — and for the other combination use \LastMark{2e-right} or \FirstMark{2e-left}.How do I get "page 3 of 12" in the footer?
\thepage\ of \pageref{LastPage} in a footer slot. It needs two compile passes because the total is only known after the last page ships out; in a multi-file project that uses \includeonly, prefer zref-lastpage, which records the value per document scope.Should I use fancyhdr, titlesec pagestyles, or the KOMA-Script options?
\pagestyleset{fancyhdr}. KOMA-Script classes have their own switches (headings=plainflat, the typearea package for page geometry) and mixing them with hand-set lengths is how most KOMA page-layout fights start.Live playground: edit the LaTeX, see it render
The preview updates as you type — break it on purpose to see how errors look.
Keep reading
Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.