[Tex/LaTex] How to place a shaded box around a section label and name

formattingframedsectioning

In working with a publisher, I need to format section headings like this (using ASCII art):

+-----+-------------------------------------+
| 1.2 |  Section name                       |
+-----+-------------------------------------+
         Texts starts here, aligned with the
         section name, and so on...

At least, that's the basic idea – more details below. That is:

  1. The section label and name should all be "boxed".

  2. The whole box extends the width of the text on the page.

  3. The section name should align with the text itself; the section label hangs into the left margin.

  4. Even more ideally, the background of the boxes containing the section number and section name should be shaded (differently: the section number is in a box with a slightly darker shade of blue that the section name).

I'd be happy with just this as a solution. But why not hope beyond hope, and tell the full story?

The actual "box" actually has rounded, not square, corners at the left extreme, so much so that the left end of the larger box is actually rounded entirely. Plus, the right end of the "box" containing the section number itself is similar. That is, the far left of the box is a rounded edge, the far right is a vertical edge, and the dividing "line" between the section number and name is rounded also. Here's an attempt in ASCI art, without the top and bottom of the boxes (I couldn't make that look any good):

( 1.2 ) Section name |

No comments on the merits of this format please :-). Just wondering if anyone knows how to do it in LaTeX. I have been playing with various packages, such as titlesec, but I cannot seem to massage this in to what the publisher would like.

I can manage point 3 above (in addition to getting font and font size about right); that's about it.

Best Answer

Here's one approach that uses the titlesec package for setting the section titles, and TikZ for drawing the bar. The section numbers are placed in a TikZ node that will grow automatically to accommodate the numbers:

\documentclass{book}
\usepackage{titlesec}
\usepackage{lipsum}
\usepackage{tikz}\usetikzlibrary{shapes.misc}
\newcommand\titlebar{%
\tikz[baseline,trim left=3.1cm,trim right=3cm] {
    \fill [cyan!25] (2.5cm,-1ex) rectangle (\textwidth+3.1cm,2.5ex);
    \node [
        fill=cyan!60!white,
        anchor= base east,
        rounded rectangle,
        minimum height=3.5ex] at (3cm,0) {
        \textbf{\arabic{chapter}.\thesection.}
    };
}%
}
\titleformat{\section}{\large}{\titlebar}{0.1cm}{}
\renewcommand*{\thesection}{\arabic{section}}
\begin{document}
\chapter{First Chapter}
\section{Section name}
\lipsum[1]
\setcounter{chapter}{9999}
\setcounter{section}{105}
\section{Section name}
\lipsum[1-2]
\end{document}
Related Question