[Tex/LaTex] How to create a header that has a colored box with page number, Chaptername, and also a line across the textwidth after it

colorheader-footerrules

I would like to create a fancy header that looks like this. I am writing a two-sided book with a5paper.
Header with line after chapter name

Best Answer

scrlayer-scrpage

Here is a suggestion using scrlayer-scrpage.

\documentclass[a5paper]{book}
\setlength\headheight{13.1pt}

\usepackage{xcolor}
\colorlet{headbgcolor}{green!50!blue!70}

\usepackage[markcase=noupper]{scrlayer-scrpage}
\clearpairofpagestyles
\automark[chapter]{chapter}
\renewcommand\chaptermarkformat{\chaptername\ \thechapter:\enskip}

\lehead*{%
  \makebox[0pt][r]{
    \colorbox{headbgcolor}{\makebox[\textwidth][r]{\pagemark\enskip}}\hspace*{1em}}%
  \headmark\hspace*{1em}\headrulefill%
}
\rohead*{%
  \headrulefill\hspace*{1em}\headmark%
  \makebox[0pt][l]{%
    \hspace*{1em}\colorbox{headbgcolor}{\makebox[\textwidth][l]{\enskip\pagemark}}}%
}

\addtokomafont{pagenumber}{\bfseries\color{white}}
\newcommand\headrulefill{\leaders\hrule width 0pt height 3pt depth -2.8pt \hfill}

\usepackage{blindtext}% dummy text
\begin{document}
\blinddocument
\end{document}

enter image description here

If the chapter page should not get the header remove the stars after \lehead and \rohead.

fancyhdr

And here is an example using fancyhdr

\documentclass[a5paper]{book}
\setlength\headheight{13.1pt}

\usepackage{xcolor}
\colorlet{headbgcolor}{green!50!blue!70}

\usepackage{fancyhdr}
\pagestyle{fancy}
\renewcommand\chaptermark[1]{\markboth{\chaptername\ \thechapter:\enskip#1}{}}
\fancyhf{}

\fancyhead[LE]{%
  \makebox[0pt][r]{
    \colorbox{headbgcolor}{\makebox[\textwidth][r]{\bfseries\textcolor{white}{\thepage}\enskip}}\hspace*{1em}}%
  {\itshape\leftmark}\hspace*{1em}\headrulefill%
}
\fancyhead[RO]{%
  \mbox{}\headrulefill \hspace*{1em}{\itshape\leftmark}%
  \makebox[0pt][l]{%
    \hspace*{1em}\colorbox{headbgcolor}{\makebox[\textwidth][l]{\enskip\bfseries\textcolor{white}{\thepage}}}}%
}
\renewcommand\headrulewidth{0pt}

\def\headrulefill{\leaders\hrule width 0pt height 3pt depth -2.8pt \hfill}

\usepackage{blindtext}% dummy text
\begin{document}
\blinddocument
\end{document}

If the chapter page should get the same header you have to redefine the fancypagestyle plain, too.

\fancypagestyle{plain}{
  \fancyhf{}
  \fancyhead[LE]{%
    \makebox[0pt][r]{
      \colorbox{headbgcolor}{\makebox[\textwidth][r]{\bfseries\textcolor{white}{\thepage}\enskip}}\hspace*{1em}}%
    {\itshape\leftmark}\hspace*{1em}\headrulefill%
  }
  \fancyhead[RO]{%
    \mbox{}\headrulefill \hspace*{1em}{\itshape\leftmark}%
    \makebox[0pt][l]{%
      \hspace*{1em}\colorbox{headbgcolor}{\makebox[\textwidth][l]{\enskip\bfseries\textcolor{white}{\thepage}}}}%
  }
}
Related Question