[Tex/LaTex] Change the color of the header line

colorfancyhdrrules

The answer to the question fancyhdr – Change horizontal line color on top of footer is not completely satisfactory, because it changes the position of the header line,
for example with this example.

\documentclass{article}

\usepackage{xcolor}
\usepackage{fancyhdr}
\renewcommand{\headrulewidth}{0.5pt}
\renewcommand{\headrule}{\hbox to\headwidth{\color{red}\leaders\hrule height \headrulewidth\hfill}}
\fancyhead[LE,RO]{Hello}
\pagestyle{fancy}

\begin{document}
    hello
\end{document}

Is it possible to change only the color of the line, without changing its position?

Best Answer

Below I save the original \headrule in \oldheadrule, and then prepend \color{<colour>} to a newly-defined \headrule that just calls \oldheadrule. The approach is similar to etoolbox's \pretocmd.

enter image description here

\documentclass{article}

\usepackage{fancyhdr,xcolor}

\let\oldheadrule\headrule% Copy \headrule into \oldheadrule
\renewcommand{\headrule}{\color{red}\oldheadrule}% Add colour to \headrule
\renewcommand{\headrulewidth}{0.5pt}
\fancyhead{Hello}
\pagestyle{fancy}

\begin{document}

Lorem ipsum\ldots

\clearpage

Lorem ipsum\ldots

\end{document}