Question
Can I force LaTeX to always keep a section with a subsection on the same page if there is nothing in between?
Situation
Let's suppose I have a section called \section{All About Monkeys}
and a subsection{Introduction}
following it. How can I ensure that there will never be a page break between the two?
Example
Here is an example of my situation. Perhaps it could be further minimized. tikz, tikzlibrary, anyfontsize
are all used by titlesec
. Thanks to Werner, I also included hyperref
, because it also affects the section spacing.
\documentclass{article}
\usepackage{fontspec}
\usepackage{lipsum}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{anyfontsize}
\usepackage{needspace}
\usepackage{hyperref}
\usepackage[explicit]{titlesec}
\newcommand{\tikzsectitle}[1]{%
\begin{tikzpicture}[remember picture,baseline,every node/.style={inner sep=0pt,outer sep=0pt}]
\path let \p1=($ (titlenumber.east)-(titlenumber.west) $)
in
node [text width=\textwidth-\x1,align=left] (titletext) {#1\strut};
\end{tikzpicture}%
}%
\newcommand{\tikzsecnumber}[1]{%
\begin{tikzpicture}[remember picture,baseline,every node/.style={inner sep=0pt,outer sep=0pt}]
\node [font=\fontsize{60}{70}\selectfont,align=left] (titlenumber) {\makebox[1em][l]{#1}};
\end{tikzpicture}%
}%
\newcommand{\tikztitleline}{%
\begin{tikzpicture}[remember picture,overlay,every node/.style={inner sep=0pt,outer sep=0pt}]
\draw ([yshift=-0ex]titletext.south west) -- ([yshift=-0ex]titletext.south east);
\end{tikzpicture}%
}%
% TITLE FORMATTING
\titleformat{\section}[hang]{\needspace{8cm}\sffamily\color{blue}\Huge\bfseries}{}{0pt}{\tikzsecnumber{\thesection}\tikzsectitle{#1}\tikztitleline{}}
\titlespacing{\section}{0pt}{40pt}{5ex plus .2ex}
% SUBSECTION
\titleformat{\subsection}[hang]{\needspace{6cm}\color{blue!85}\Large\bfseries}{\thesubsection\quad}{0pt}{#1}
\titlespacing*{\subsection}{0pt}{3.25ex plus 1ex minus .2ex}{1.5ex plus .2ex}
\begin{document}
\lipsum[1-2]
Monkeys are haplorhine (dry-nosed) primates, a group generally possessing tails and consisting of approximately 260 known living species. Many monkey species are tree-dwelling (arboreal), although there are species that live primarily on the ground, such as baboons.
\section{All About Monkeys}
\subsection{Introduction}
\lipsum[1]
\end{document}
Output
The following is an example of what should never occur:
titlesec
,needspace
, and I have some weirdtikz
things going on in the sectioning commands. I think I will leave out thetikz
if that is ok.hyperref
- it also plays a part in sectional units.