23

I posted this at stackoverflow and got redirected here. This does indeed look like a better place to ask.

I would like to decorate my headlines (section, subsection, etc.) by adding a background color. I would like this box filled with a single solid color to span across the entire typearea.

This picture is a screenshot of an OpenOffice document where the headline has the formating, layout and color I want.

Image showing example

Requirements on a solution

  1. The resulting style is supposed to be used by others, meaning an equivalent latex output to the picture above shall be created by this code:

    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text 
    
    \subsubsection{This is a headline}
    
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text
    
  2. If the section is supposed to be unnumbered one should be using \subsubsection*.

  3. LaTeX still needs to be in charge of the whitespace between paragraphs and the blue box.

What I have tried so far

As far as I can google the headline together with the section numbering are a simple paragraph. Latex adds some skips before and after and squeezes in a few commands that modify the font(s).

My ideas revolve around locking this paragraph in a \colorbox. The colorbox macro works like this: \colorbox{color}{the content around which to draw a box filled with the specified color}. My problem is I can't get a grasp on this paragraph.

The easy 80%

My work is based on koma-script and by redefining \othersectionlevelsformat and \(sub)*section. I can draw two boxes, one surrounding the section numbering and another surrounding the section title. However this has 3 open issues:

  1. the upper edges of the boxes are unaligned and the box with the title is slightly larger than the line with the numbering
  2. The box around the title does not strech to the right end of the typearea
  3. the box around the numbering doesn't grow if the title spans multiple lines (no surprise here)

The hard 20%

I tried to make latex put the section numbering into a \savebox I could access later and put as part of the title. That would eliminate the need for two boxes and solve all three of my problems at once, but that doesn't work. I only get to modify the title before the actual numbering is done. So while I can put the numbering into a savebox, I can't do anything with it until it's too late.

I tried putting the \section ... statement into a colorbox, but it doesn't like that and the document fails to compile with ! LaTeX Error: Something's wrong--perhaps a missing \item. The same holds for saveboxes. I guess colorbox uses those.

I tried putting the \section ... statement in a minipage and put a box around that. This has two issues. 1st: latex doesn't put any empty space above a section. 2nd: not only the section numbering and title have the background but also the empty space between section title and first paragraph.

So how can one hack latex to do a section title formating as shown in the screenshot above?

5
  • Thanks for the quick replys, but using titlesec breaks out of koma-script and the tikz approach can't adapt the rectangle to the actual height (esp. if multiline) of the headline. However, I think the titlesec approach can be modified to honor koma-settings and fix my problems. Thanks again!
    – Bananguin
    Jan 5, 2012 at 11:26
  • Because you’re using KOMA script – Markus Kohm himself provided a solution almost exactly 6 years ago: Farbig unterlegte Überschriften. He stated, that this works only for one lined section titles!
    – Speravir
    Jan 6, 2012 at 0:06
  • For solutions that does not use KOMA script, see Background color in Section titles - TeX - LaTeX Stack Exchange
    – user202729
    Nov 3, 2021 at 1:12
  • 1
    @user202729 egreg's answer below does not use KOMA
    – Bananguin
    Nov 3, 2021 at 6:57
  • Ah right. Looks like they're mostly the same approach (titlesec + colorbox + absorb the content as parameter of command)
    – user202729
    Nov 3, 2021 at 8:12

5 Answers 5

9

Here my second try. It is using the same Idea as Sharpie, but doesn't need tikz.

\documentclass{scrartcl}

\usepackage{xcolor}
\usepackage{lipsum}

\setkomafont{section}{\mysection}
\newcommand{\mysection}[1]{%
    \Large\sf\bf%
    \setlength{\fboxsep}{0cm}%already boxed
    \colorbox{orange!80}{%
        \begin{minipage}{\linewidth}%
            \vspace*{2pt}%Space before
            #1
            \vspace*{2pt}%Space after
        \end{minipage}%
    }}

    \begin{document}

        \section{Example section}
        \lipsum[1]

        \section*{A very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long section}
        \lipsum[1]
\end{document}

result is: result feel free to adopt for subsection etc ;)

1
  • This is what I was looking for! To round it off I use \addtokomafont instead of \setkomafont. That way koma-script's settings remain in tact, I don't need the line "\Large\sf\bf%" and I only need to add lines \addtokomafont{subsection
    – Bananguin
    Jan 9, 2012 at 8:41
26

The solution below use \titleformat command in titlesec package, the last command in the before-code argument (\colorsection) is used to wrap the title in a \colorbox (in color package) to change the background color.

This is for a section, but you can extend it easily for subsections with a similar scheme:

\documentclass[a4paper]{scrbook}
\usepackage{xcolor,lipsum}
\usepackage{titlesec}

\titleformat{name=\section}[block]
  {\sffamily\large}
  {}
  {0pt}
  {\colorsection}
\titlespacing*{\section}{0pt}{\baselineskip}{\baselineskip}

\newcommand{\colorsection}[1]{%
  \colorbox{blue!20}{\parbox{\dimexpr\textwidth-2\fboxsep}{\thesection\ #1}}}

\begin{document}

\lipsum[1]
\section{This is the title}
\lipsum[2]
\end{document}

If you want white on colored text, just modify the \colorsection command, for example as

\newcommand{\colorsection}[1]{%
  \colorbox{blue}{\parbox{\dimexpr\textwidth-2\fboxsep}{\color{white}\thesection\ #1}}}

enter image description here

5
  • What about \section* (stared version of \section command)? Please mention the option numberless after block in the command for stared version of your answer.
    – Qaher
    Oct 10, 2020 at 18:07
  • @egreg How would one eliminate the numbering from the sections?
    – Sam Y.
    Feb 10, 2022 at 22:36
  • @SamY. Remove \thesection\
    – egreg
    Feb 10, 2022 at 22:41
  • @egreg Nice! That saved me so much time searching around! One other thing, though: The numbers in the body of the paper are now gone, but at the very top of my TOC page there is a small (about 1mm wide x 2mm high) blue rectangle. Do you know how to eliminate this off hand, or should I post a full-blown question with a MWE?
    – Sam Y.
    Feb 10, 2022 at 23:04
  • @SamY. Please, do. There might be some different details.
    – egreg
    Feb 10, 2022 at 23:06
17

Here is a suggestion redefining the new command \sectionlinesformat that is explained in the documentation of version 3.19 or newer:

\documentclass{scrartcl}[2015/09/15]
\usepackage{blindtext}% dummy text
\usepackage{xcolor}
\colorlet{sectioncolor}{orange}
\makeatletter
\renewcommand\sectionlinesformat[4]{%
  \colorbox{sectioncolor}{%
    \parbox[t]{\dimexpr\textwidth-2\fboxsep\relax}{%
      \raggedsection\color{white}\@hangfrom{#3}{#4}%
}}}
\makeatother
%\renewcommand\raggedsection{\centering}
\begin{document}
  \section{Example section}
  \blindtext
  \section{A very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long section}
  \blindtext
  \addsec{A very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long section}
  \blindtext
  \blinddocument
\end{document}

enter image description here

It is also possible to use different colors for sections, subsections and subsubsections:

\documentclass{scrartcl}[2015/09/15]
\usepackage{blindtext}% dummy text
\usepackage{xcolor}
\colorlet{sectioncolor}{orange}
\colorlet{subsectioncolor}{purple}
\colorlet{subsubsectioncolor}{blue!50!black}
\makeatletter
\renewcommand\sectionlinesformat[4]{%
  \colorbox{#1color}{%
    \parbox[t]{\dimexpr\textwidth-2\fboxsep\relax}{%
      \raggedsection\color{white}\@hangfrom{#3}{#4}%
}}}
\makeatother
%\renewcommand\raggedsection{\centering}
\begin{document}
  \section{Example section}
  \blindtext
  \section{A very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long section}
  \blindtext
  \addsec{A very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long section}
  \blindtext
  \blinddocument
\end{document}

enter image description here


The second argument (#2) of \sectionlinesformat is the indent of the section heading that you can set using \RedeclarSectionCommand. Here is an example using an negative indent to enlarge the section heading into the left margin:

\documentclass{scrartcl}[2015/09/15]
\usepackage{blindtext}% dummy text
\usepackage{xcolor}
\colorlet{sectioncolor}{orange}
\colorlet{subsectioncolor}{purple}
\colorlet{subsubsectioncolor}{blue!50!black}
\makeatletter
\renewcommand\sectionlinesformat[4]{%
  \hspace{#2}%
  \colorbox{#1color}{%
    \parbox[t]{\dimexpr\textwidth-2\fboxsep-#2\relax}{%
      \raggedsection\color{white}\@hangfrom{#3}{#4}%
}}}
\makeatother
\RedeclareSectionCommand[indent=-1em]{section}
%\renewcommand\raggedsection{\centering}
\begin{document}
  \section{Example section}
  \blindtext
  \section{A very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long section}
  \blindtext
  \addsec{A very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long section}
  \blindtext
  \blinddocument
\end{document}

enter image description here

3
  • For completeness sake, could you tell us what #2 in \sectionlinesformat does?
    – Bananguin
    Sep 28, 2015 at 16:02
  • I have added an example that also uses #2.
    – esdd
    Sep 28, 2015 at 19:51
  • I like this new feature very much, but can only upvote once. :-)
    – Bananguin
    Sep 29, 2015 at 7:54
8

I have a different approach. I used tikz:

\documentclass[12pt]{scrartcl}
\usepackage{tikz}
\makeatletter
    \setkomafont{section}{\color{white}%
        \bfseries\Large
        \begin{tikzpicture}[overlay]
        \draw[fill=blue] (0,-2pt) rectangle
        (\linewidth,16.4pt);
        \end{tikzpicture}}

\begin{document}
\section{test}
\subsubsection{This is a headline}
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text 

\section*{test 2}
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text Some Text Some Text
    Some Text Some Text Some Text Some Text Some Text
\end{document}

The result is this (you can change the color blue to match your color):

result

of cause you can easily adopt this for subsection etc...

1
  • 1
    something to be aware of with Tikz is that Tikz does not fully suppor the CMYK colour model, so if you pass in cmyk colours they get converted to RGB. Mar 31, 2017 at 4:25
6

Here is another method that exploits the behavior of passing a macro that takes one argument to \setkomafont. The actual styling is done using TikZ nodes.

\documentclass{scrartcl}

\usepackage{tikz}
\usepackage{lipsum}

\tikzset{
  % Styling of header text is done using key/value options for TikZ nodes. See
  % section 16.4 of the PGF manual for a complete list of options that affect
  % text.
  headings/base/.style = {
    % Zap node seperation, set text width and alignment.
    outer sep = 0pt,
    % Trim off 2/3rd of an em to compensate for the inner xsep which spaces the
    % text nicely away from the left side, but causes the node to hang into the
    % right margin.
    text width = {\textwidth - 0.6666em},
    align = left,
    text = white,
  },
  headings/section/.style = {
    headings/base,
    fill = blue!50,
    font = \sffamily\Large
  },
  headings/subsection/.style = {
    headings/base,
    fill = blue!25,
    font = \sffamily\large
  }
}

\newcommand{\colorboxedsec}[2]{%
  \tikz{\node[headings/#1]{#2};}}

\setkomafont{section}{\colorboxedsec{section}}
\setkomafont{subsection}{\colorboxedsec{subsection}}


\begin{document}

\section{Lorem Ipsum}
  \lipsum[1]

\subsection{History of Lorem Ipsum}
  Foo bar baz.

\section*{A section header full of \lipsum[1]}

\end{document}

The results:

enter image description here

3
  • great solution. How did you know that Koma will pass the command? I haven't read this in documentation. I just played with this function and build a non tikz multi line version.
    – someonr
    Jan 6, 2012 at 0:38
  • It was a guess. If KOMA executes something like \sectionfont\sectiontext but \sectionfont has been defined to take one argument, the result will behave like \sectionfont{\sectiontext}.
    – Sharpie
    Jan 6, 2012 at 0:39
  • thx. Only problem is that the koma script authors may change it any time, because this is not an official feature. Anyway I like this solution.
    – someonr
    Jan 6, 2012 at 1:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .