[Tex/LaTex] insert text into hrulefill

rules

Is there a simple way to have text that looks like this?

--- text ---

where the --- fills a certain width? I've tried

\centerline{\rule{2cm}{.4pt}text\rule{2cm}{.4pt}}

but here if "text" is "text_1" in one case and "text_123" in another, then the total width of the text plus rule varies in each case.

Best Answer

You can use \leaders to specify the style of your rules:

enter image description here

\documentclass{article}
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\newcommand*{\myrulefill}[3][]{%
  \makebox[#2]{#1%
    \leaders\hrule height \dimexpr.5ex+.2pt\relax depth \dimexpr -.5ex+.2pt\relax \hfill% Left rule
    \enskip{#3}\enskip% Text (and surrounding spaces)
    \leaders\hrule height \dimexpr.5ex+.2pt\relax depth \dimexpr -.5ex+.2pt\relax \hfill\kern0pt}% Right rule
}
\begin{document}
\myrulefill{10em}{text} \par
\myrulefill{.5\linewidth}{Here is some more text} \par
\myrulefill[\color{olive}]{150pt}{\color{black}SoMe MoRe TeXT}
\end{document}

The provided \myrulefill[<stuff>]{<len>}{<text>} inserts <text> in the middle of a box of length <len> with rules added on either side. <stuff> is an optional argument that can be specified if you want to (say) change the colour.