[Tex/LaTex] \newcommand for centered \section

sectioningtitlesec

I am trying to use the titlesec package to achieve this but I'm not certain as to what the syntax should be…

\usepackage{titlesec}

\newcommand{\centeredsection}{\titleformat{\section}{\centering}}

Thanks for your help.

Best Answer

If you want all section titles centered, it suffices to use the starred form of \titleformat in this way:

\titleformat*{\section}{\centering\normalfont\Large\bfseries}

MWE:

\documentclass{article}
\usepackage{titlesec}

\titleformat*{\section}{\centering\normalfont\Large\bfseries}

\begin{document}

\section{test}
Some text

\end{document}

Output:

enter image description here

Instead, if you are trying to create a new sectioning command which have a centered title, this can not be done in this way (supposing you are using the article class):

\makeatletter
\newcommand\centeredsection{\@startsection {section}{1}{\z@}%
                                   {-3.5ex \@plus -1ex \@minus -.2ex}%
                                   {2.3ex \@plus.2ex}%
                                   {\centering\normalfont\Large\bfseries}}
\makeatother

MWE:

\documentclass{article}

\makeatletter
\newcommand\centeredsection{\@startsection {section}{1}{\z@}%
                                   {-3.5ex \@plus -1ex \@minus -.2ex}%
                                   {2.3ex \@plus.2ex}%
                                   {\centering\normalfont\Large\bfseries}}
\makeatother


\begin{document}

\centeredsection{Centered section}
Some text

\section{Normal section}
Some text

\end{document} 

Output:

enter image description here

Related Question