I would like to redefine the \section and \section* to produce section titles that look roughly like this:
that is, text in white over a black bar that extends from left to right margin. I don't anticipate any section titles being longer than one line.
Asked
Active
Viewed 5,132 times
14
JohnReed
- 2,627
thecommexokid
- 1,189
-
Related Q&A's: Shaded box around multiline section heading?, How to place a shaded box around a section label and name. – Nikos Alexandris Oct 14 '12 at 16:10
1 Answers
21
Here's one possible solution using the explicit option for the titlesec package:
\documentclass{article}
\usepackage[explicit]{titlesec}
\usepackage{xcolor}
\usepackage{lipsum}
\titleformat{\section}
{\normalfont\Large\bfseries}{}{0em}{\colorbox{black}{\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\textcolor{white}{\thesection\quad#1}}}}
\titleformat{name=\section,numberless}
{\normalfont\Large\bfseries}{}{0em}{\colorbox{black}{\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\textcolor{white}{#1}}}}
\begin{document}
\section{A Test Section}
\lipsum[4]
\section{Another Test Section}
\lipsum[4]
\section{Another Test Section with a long title spanning more than one line}
\lipsum[4]
\section*{An Unnumbered Test Section}
\lipsum[4]
\end{document}
The idea is to use a \parbox of width equal to \textwidth (-2\fboxsep) inside a black \colorbox; inside this \colorbox the text is set to white using \textcolor.

pluton
- 16,421
Gonzalo Medina
- 505,128
-
This solution does not exhibit the expected behavior with
\section*(it correctly does not incrementthesection, but it still displays it). It also adds a lot of undesirable extra vertical space above and below the section title. – thecommexokid Jun 07 '12 at 02:36 -
Hadn't seen your edit yet. First objection retracted. Second still stands. – thecommexokid Jun 07 '12 at 02:37
-
-
Is very nice now, yes. Could you explain what all the parts are doing? – thecommexokid Jun 07 '12 at 02:41
-
4@thecommexokid I've added a brief explanation;
\titleformatis explained in the documentation oftitlesec. – Gonzalo Medina Jun 07 '12 at 02:45