Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I'd like to use titlesec to typeset a section header that would look like this:

--------- Name of Section ------------

(the ---- would be a rule, and the entire section header would be centered)

I've looked at the titlesec documentation, but I'm a little confused as to how to do this. Any help would be greatly appreciated.

share|improve this question
add comment

1 Answer 1

up vote 14 down vote accepted

You can do something along these lines; the \varhrulefill command is a variant of \hrulefill, but lifting the line above the baseline:

\documentclass{article}
\usepackage[explicit]{titlesec}

\newcommand*\varhrulefill{%
  \leavevmode\leaders\hrule height 0.6ex depth -0.5ex\hfill\kern0pt}

\titleformat{\section}
  {\normalfont\Large\bfseries\filcenter}{}{0em}{\varhrulefill\enspace#1\enspace\varhrulefill}

\begin{document}

\section{A Test Section}

\end{document}

enter image description here

In case of titles spanning more than one line, a little more work needs to be done: now the tile is placed inside a \parbox with centered contents; the width of the \parbox is calculated as the minimum between the length of the title and 0.7\textwidth (this value can be changed), and then the \parbox is placed in the center with the two surrounding rules:

\documentclass{article}
\usepackage{calc}
\usepackage[explicit]{titlesec}
\usepackage{lipsum}

\newlength\Titlewd
\newlength\TitleBox

\newcommand*\varhrulefill{%
  \leavevmode\leaders\hrule height 0.6ex depth -0.5ex\hfill\kern0pt}

\titleformat{\section}
  {\normalfont\Large\bfseries\filcenter}{}{0em}{%
  \settowidth\Titlewd{\Large\bfseries#1}%
  \setlength\TitleBox{\minof{\Titlewd}{.7\textwidth}}%
  \varhrulefill\enspace\parbox{\TitleBox}{\centering #1}\enspace\varhrulefill}
\titlespacing*{\section}
  {0pt}{4.5ex plus 1ex minus .2ex}{2.3ex plus .2ex}

\begin{document}

\section{A Test Section}
\lipsum[2]
\section{A Test Section with a long title spanning more than one line}
\lipsum[2]

\end{document}

enter image description here

Notice that even though the section number is not included in the title (in the document body), it still will appear in an eventual table of contents; to remove the section number from the ToC, the following lines can be added to the preamble:

\usepackage{titletoc}

\titlecontents{section}
  [0em]{\bfseries}{}{}
  {\hfill\contentspage}[\addvspace{10pt}]
share|improve this answer
    
Amazing. Just amazing :) –  Suresh May 25 '12 at 1:46
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.