[Tex/LaTex] Change color of a type of text like header/footer

colorfancyhdrheader-footer

Can we change the color of a logical type of text, say every header or every footer, by a single command? Header and footer is using fancyhdr.

I believe it should be a \renewcommand but won't it affect dependent packages like fancyhdr? I could define newer macros from the one which fancyhdr uses like \rfoot or \cfoot, to say \rfootcolored or \cfootcolored. But then I have to redesign the entire header/footer from scratch…which I don't want to do..

A MWE..

\documentclass{book}

\usepackage{lipsum}
\usepackage{fancyhdr}


\begin{document}
\pagestyle{fancy}

\chapter{Lipsum}
\lipsum[1-6]

\section{lipsumsection}
\lipsum[7-10]

\chapter{Lipsum2}
\lipsum[2-7]



\end{document}

Best Answer

You may use the etoolbox package to patch the internal fancyhdr macros \f@nch@head and \f@nch@foot (and in case you want colored rules, also \headrule and \footrule):

\documentclass{book}

\usepackage{lipsum}
\usepackage{fancyhdr}
\usepackage{xcolor}

\usepackage{etoolbox}

\makeatletter
\patchcmd{\f@nch@head}{\rlap}{\color{red}\rlap}{}{}
\patchcmd{\headrule}{\hrule}{\color{red}\hrule}{}{}
\patchcmd{\f@nch@foot}{\rlap}{\color{green}\rlap}{}{}
\patchcmd{\footrule}{\hrule}{\color{green}\hrule}{}{}
\makeatother

\begin{document}
\pagestyle{fancy}

\chapter{Lipsum}
\lipsum[1-6]

\section{lipsumsection}
\lipsum[7-10]

\chapter{Lipsum2}
\lipsum[2-7]

\end{document}

enter image description here

Related Question