7

I use \usepackage[explicit]{titlesec} to customize the design of my sections, subsections... In particular, i have :

\titleformat{\section}%
{\large\sffamily\bfseries}%
{My Section \arabic{section} }%
{0.5em}%
{#1}% \\ \hspace*{-1.5cm}
[{\color{blue}\titlerule[2.5pt]}]

where the {\color{blue}\titlerule[2.5pt]} produces an underline. The problem is, that a page breaking can happen just after the section title, and the line would appear on the next page. Is there a way to prevent that ?

EDIT : Minimal Example:

\documentclass[12pt]{article}
\usepackage[explicit]{titlesec}
\usepackage[dvipsnames]{xcolor}

\titleformat{\section}%
{\large\sffamily\bfseries}%
{Section \arabic{section}}%
{0.5em}%
{#1}% \\ \hspace*{-1.5cm}
[{\color{blue}\titlerule[2.5pt]}]

\begin{document}

\section{titre1}
blabla  
\vspace{16cm}\\
blabla  
\section{titre2}
blabla blabla 
\end{document}
David Carlisle
  • 757,742
Loic Rosnay
  • 8,167

1 Answers1

9

Replace {\color{blue}<rule definition>} with \textcolor{blue}{<rule definition>}.

\documentclass[12pt]{article}
\usepackage[explicit]{titlesec}
\usepackage[dvipsnames]{xcolor}

\titleformat{\section}%
{\large\sffamily\bfseries}%
{Section \arabic{section}}%
{0.5em}%
{#1}% \\ \hspace*{-1.5cm}
[\textcolor{blue}{\titlerule[2.5pt]}]

\begin{document}

\section{titre1}
blabla  
\vspace{16cm}\\    blabla  
\section{titre2}
blabla blabla 
\end{document}

EDIT: Note that this solution produces unwanted additional vertical space between title and underline. See Strange behaviour of titlesec, with colored titlerule and particularly egreg's answer for a solution to this follow-up problem.

Ulrike Fischer
  • 327,261
lockstep
  • 250,273
  • ok, great! Thanks. But why does it works ? – Loic Rosnay Jan 02 '12 at 11:33
  • Not sure, but \color is one of the commands that tend to disguise spacing commands and penalty values (here: the penalty for page breaks). – lockstep Jan 02 '12 at 11:35
  • I just noticed a annoying thing : with \textcolor instead of \color, this prevents the pagebreaking, but on the other hand, the vertical space between the text and the underline is increased... – Loic Rosnay Jan 04 '12 at 14:57
  • @nicolasroy I've no idea right now what causes this. Perhaps titlesec allows to add some negative vertical space to correct the observed effect. If nothing helps, please ask a follow-up question. – lockstep Jan 04 '12 at 15:02
  • 1
    @lockstep: the reason why \color introduces a break point is because it calls a \write which introduces a whatsit. You can see this by replacing {\color{blue}\titlerule[2.5pt]} with {\write-1{}\titlerule[2.5pt]}. To solve the problem, no need for \textcolor, {\color{blue}\nobreak\titlerule[2.5pt]} is enough. – Philippe Goutet Jan 05 '12 at 12:35