How do I center the table of contents title using tocloft?
There's indeed something in the example code of the tocloft
package that's not quite correct about how to get the string "Contents" centered on a line. Anyway, you can achieve your objective by issuing the commands
\renewcommand{\contentsname}{\hfill\bfseries\Large Contents\hfill}
\renewcommand{\cftaftertoctitle}{\hfill}
Note the \hfill
inserted after "Contents". If you would rather have the string "Contents" be set in normal size and normal weight, you'd use \normalfont\normalsize
instead of \bfseries\Large
.
A full MWE, applying these changes to the header of the List of Tables as well:
\documentclass{article}
\usepackage{tocloft}
\renewcommand{\contentsname}{\hfill\bfseries\Large Contents\hfill}
\renewcommand{\cftaftertoctitle}{\hfill}
\renewcommand{\listtablename}{\hfill\bfseries\Large List of Tables} % no \hfill after "List of Tables"...
%%% using the command "\renewcommand{\cftlottitlefont}{\hfill\bfseries\Large}" works too...
\renewcommand{\cftafterlottitle}{\hfill}
\begin{document}
\tableofcontents
\listoftables
\section{Section}
\begin{table}[h]
\centering
\begin{tabular}{| l | c | r |}
\hline
1 & 2 & 3 \\
\hline
\end{tabular}
\caption[Example table]{This is a table.}
\end{table}
\end{document}
Actually your solution is almost correct. The reason why it is not working is the fact that LaTeX removes the horizontal space that comes at the end of a line. This answer further elaborates on this fact but to prevent this either you need to insert a dummy text -- e.g., \null{}
, \mbox{}
, \hfill
-- after the last \hfill
:
\renewcommand{\cfttoctitlefont}{\hfill\Large}
\renewcommand{\cftaftertoctitle}{\hfill\hfill} %Note the second \hfill, it could have been any dummy text
and Mico's solution effectively does that by ending \contentsname
with an \hfill
and simultaneously setting \cftaftertoctitle
to \hfill
.
Or, you could use \hspace*{\fill}
so that your code becomes:
\renewcommand{\cfttoctitlefont}{\hspace*{\fill}\Large}
\renewcommand{\cftaftertoctitle}{\hspace*{\fill}}
and Mico's solution becomes:
\renewcommand{\contentsname}{\hspace*{\fill}\bfseries\Large Contents\hspace*{\fill}}
%\renewcommand{\cftaftertoctitle}{\hspace*{\fill}} % Alternatively, you can delete the last \hspace*{\fill} from the above line and uncomment this line.
This last \contentsname
definition works with both tocloft
package and the original LaTeX toc command as well.