[Tex/LaTex] Right/left aligning with fancyhdr

fancyhdr

I cannot wrap my head around fancyhdr and a two-paged document. This is what I have now:

\pagestyle{fancy}
\renewcommand{\chaptermark}[1]{ \markboth{#1}{} }
\renewcommand{\sectionmark}[1]{ \markright{\nameOfBook{}} }

\fancyhf{}
\fancyhead[LE,RO]{\thepage}
\fancyhead[RE]{\textbf{ \nouppercase{Kapitel \thechapter: \leftmark}} }
\fancyhead[LO]{\textbf{ \nouppercase{\rightmark}} }

\fancypagestyle{plain}{ %
  \fancyhf{} % remove everything
  \renewcommand{\headrulewidth}{0pt} % remove lines as well
  \renewcommand{\footrulewidth}{0pt}
}

This is what I get:

enter image description here

What I would like to have is that the header text on the left page is left aligned (with respect to the page number, giving a small room), and similar for the right page. I don't know if it's a good solution (visually) or if I should aim on page numbers at the bottom while keeping the texts at the top. To be able to decide I need to be able to align the text first, but I fail to do that.

Question: How do I left/right align the header texts while respecting a small area reserved for the page numbers?

Best Answer

You can put all the material in the left or right header as needed, with the page number in a box of fixed width using the \makebox macro and the other text immediately after or before corresponding to even or odd pages. The syntax for \makebox is

\makebox[width][pos]{Text}

with pos one of l, r or c, for left, right or centered material within the box. It is good to specify the width in units that depend on the font, such as em. Below I have used 1.5em, which gives you space for a three digit page number.

Left page:

Sample left page

Right page:

Sample right page

\documentclass{book}

\usepackage{fancyhdr}

\pagestyle{fancy}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\markright{The Book Title}}

\fancyhf{}
\fancyhead[LE]{\makebox[1.5em][l]{\thepage}\textbf{\nouppercase{Kapitel \thechapter: \leftmark}}}
\fancyhead[RO]{\textbf{\nouppercase{\rightmark}}\makebox[1.5em][r]{\thepage}}

\fancypagestyle{plain}{ %
  \fancyhf{} % remove everything
  \renewcommand{\headrulewidth}{0pt} % remove lines as well
  \renewcommand{\footrulewidth}{0pt}
  }

\usepackage{lipsum}

\begin{document}
\setcounter{page}{21}
\chapter{Some chapter title}
\section{A section of some sort}

\lipsum[1-10]
\end{document}

Beware of spaces added in your macros - for example, your orginal code added a space before Kapitel, which I have removed above.