Show only chapter number and chapter title as well as book title in header using fancyhdr

fancyhdrheader-footer

I am writing a book in which I want to customize the headers and footers for the main matter. I want it to have the following style:

  • nothing to be printed in the footer – (\fancyfoot{})
  • page number on the Even-Right and Odd-Left pages – \fancyhead[ER,OL]{\thepage}
  • book title on the even pages, close to the page number
  • chapter number and chapter title on the odd pages, close to the page number (called with \thechapter)

I want to create a new style with:

\fancypagestyle{mainmatterstyle}{%
   \fancyfoot{}
   \fancyhead[ER,OL]{\thepage}
   the additional commands go here
}

Can anyone address me on how to do that?

I started reading the fancyhdr manual today and got stuck in section 15. I didn't understand the \rightmark, \leftmark, \markboth and \markright scoop.

My document has the following structure:

\documentclass{book}
\usepackage{fancyhdr}
\fancypagestyle{mainmatterstyle}{
   % ⟨as above⟩
}
\title{My Book Title}
\author{Tush}
\begin{document}
\frontmatter
\maketitle
\tableofcontents
\mainmatter
\pagestyle{mainmatterstyle}
\chapter{The first chapter}
   % ...Text goes here...
\end{document}

Is there a command, something like \thebooktitle, that prints the argument of \title{}?

Best Answer

You can do the following:

\documentclass{book}
\usepackage{fancyhdr}
\title{My Book Title}
\author{Tush}

\makeatletter
\let\thetitle\@title
\makeatother

\renewcommand{\chaptermark}[1]{\markboth{\thechapter. #1}{\thetitle}}

\fancypagestyle{mainmatterstyle}{%
   \fancyfoot{}
   \fancyhead{}
   \fancyhead[ER]{\rightmark\makebox[3em][r]{\thepage}}
   \fancyhead[OL]{\makebox[3em][l]{\thepage}\leftmark}
}

\usepackage{lipsum}
\begin{document}
\frontmatter
\maketitle
\tableofcontents
\mainmatter
\pagestyle{mainmatterstyle}
\chapter{The first chapter}

\lipsum[1-10]

\end{document}

enter image description here

enter image description here

Let me quickly explain this: The title is internally stored in the macro \@title. To make it more easily accessible, I defined a new non-@ macro \thetitle to have the same contents using \let.

I then redefine the \chaptermark macro that is called every time a new \chapter starts and whose first argument (#1) is the chapter title. I tell this macro to call \markboth which takes two arguments: the mark for the left page and the mark for the right page, that can later be called using \leftmark and \rightmark. Here, I use the \thetitle macro that I defined before.

The two macros \leftmark and \rightmark then can eventually be placed inside the \fancyhead macro(s) to get the headers you want.

Related Question