I wanted to know whether there is a way to set the background color of my header. Here is my code so far:

\usepackage{fancyhdr}
\usepackage{lastpage}
\pagestyle{fancy}
\fancyhf{}
%\renewcommand{\footrulewidth}{0pt}


\documentclass{article}

\usepackage{fancyhdr,color}
\usepackage{lastpage}

\pagestyle{fancy}
\fancyhf{}
\hspace{-\textwidth}%
\textcolor{white}{\textsl{Title}}}

\begin{document}
zz
\end{document}

• This somehow shifts "Title" a bit to the right, but the "Page of..." is completely on the left (and because of the italics a bit of the last character is outside the box) Dec 31, 2020 at 16:42
• Okay I found out why it shifted the "Title": I didn't have the code all in one line. But, I could'nt figure out, how to move the "Page of..." more to the right. Dec 31, 2020 at 16:52
• Play with phantom. \rhead{\textcolor{white}{\textsl{\Page \thepage{} of \pageref{LastPage}\phantom{xx}}}} will move the right header to the left to deal with the italics. Dec 31, 2020 at 16:59

You can set the header in a \colorbox in the centre only, and then spread the contents to the left/right/centre as needed.

\documentclass{article}

\usepackage{fancyhdr,xcolor}
\usepackage{lastpage,lipsum}

\pagestyle{fancy}
\fancyhf{}
\setlength{\fboxsep}{0pt}% Remove \fbox gap
\colorbox{blue!15!white}{%
\makebox[\textwidth]{%
\hfill
\hfill
\llap{\textsl{Page \thepage\ of \pageref{LastPage}}}% Right header
}% \makebox
}% \colorbox

\begin{document}

\sloppy\lipsum[1-50]

\end{document}


All elements are placed with zero width (via \rlap for the left header, \clap for the centre and \llap for the right header) so as to not affect its placement relative to their width.

• What exactly is a fbox? Dec 31, 2020 at 19:00
• I like this solution more, but I have one problem with it. How do I make the box taller? Dec 31, 2020 at 19:05
• @Brain: It's shorthand for a framed box that has a rule around it (of width \fboxrule) and a gap of \fboxsep between the rule and the box content. There is a more elaborate \framebox command as well that does the same thing with a set of optional arguments for the content width and alignment (similar to \makebox).
– Werner
Dec 31, 2020 at 19:07
• @Brain: It depends. If you just want a little more room, add a \strut just before \rlap. If you want it much taller, then one can insert a strut of your liking, but you'll also have to change \headheight. Removing the \fboxsep (setting it to 0pt in my answer) makes the box tight against the content. One could use the default \fboxsep but, again, it may require a change in \headheight as well. You'll receive a warning to that effect in the .log. It can be circumvented, but you'll have to be specific about your needs though.
– Werner
Dec 31, 2020 at 19:09
• When I add a \strut, the header get's too long. How would I go about fixing that? Jan 2, 2021 at 20:03