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 would like to redefine the \section and \section* to produce section titles that look roughly like this: illustration of desired section title formatting 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.

share|improve this question

1 Answer 1

up vote 14 down vote accepted

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.

enter image description here

share|improve this answer
    
This solution does not exhibit the expected behavior with \section* (it correctly does not increment thesection, but it still displays it). It also adds a lot of undesirable extra vertical space above and below the section title. –  thecommexokid Jun 7 '12 at 2:36
    
Hadn't seen your edit yet. First objection retracted. Second still stands. –  thecommexokid Jun 7 '12 at 2:37
    
@thecommexokid see my updated answer. Is that what you want? –  Gonzalo Medina Jun 7 '12 at 2:39
    
Is very nice now, yes. Could you explain what all the parts are doing? –  thecommexokid Jun 7 '12 at 2:41
3  
@thecommexokid I've added a brief explanation; \titleformat is explained in the documentation of titlesec. –  Gonzalo Medina Jun 7 '12 at 2:45

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.