Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override background color for subsection titles in LaTeX

Tags:

latex

pdflatex

LaTeX newbie here.

I need to set background color for all my \subsection titles. Whole line should change color, not only the part of it with text.

This does work:

\subsection{\colorbox{Gray}{Title}}

But it does not color whole line. Also I'd like to configure it in a single place for all \subsections.

My google-fu is failing me. Any suggestions on how to do what I want?

like image 812
Alexander Gladysh Avatar asked Feb 27 '23 09:02

Alexander Gladysh


2 Answers

To make the \colorbox the width of the line, use \makebox:

\subsection{\colorbox{Gray}{\makebox[\hfill][l]{Title}}}

I'm not 100% sure "\hfill" is what you need to put in the first set of square brackets. You may need to experiment with that part. An alternative worth trying is

\subsection{\colorbox{Gray}{\makebox[\width][s]{Title\hfill}}}

To configure it in one place for all subsections, the easiest thing to do is define a wrapper command:

\newcommand{\mysubsection}[1]
  {\subsection{\colorbox{Gray}{\makebox[\hfill][l]{#1}}}}

You could also redefine \subsection, but then you have to learn about the internal commands it uses and take care to match your documentclass's other formatting. I don't recommend it.

like image 53
zwol Avatar answered Mar 23 '23 16:03

zwol


Expanding on Zack's answer, this is my solution:

If you want the text left aligned

\newcommand{\mysubsection}[1]{
    \setlength\fboxsep{4pt} %% spacing around box contents
    \subsection*{\colorbox{bgcol}{\makebox[\textwidth][l]{\color{textcol}#1\hfill}}}
}

or if you want it centred

\newcommand{\mysubsection}[1]{
    \setlength\fboxsep{4pt} %% spacing around box contents
    \subsection*{\colorbox{bgcol}{\makebox[\textwidth]{\color{textcol}#1}}}
}

You can drop the local declaration of \setlength\fboxsep if you are using a global setting. Obviously bgcol and textcol need to be defined earlier in the document preamble.

If are in the multicols environment you can use \textwidth or \columnwidth, or a relative amount of either these, depending on how you have things laid out and how you want them to look.

I am using multicols with the text spanning 100% of the column. But found that using either \textwidth or \columnwidth the headings overhang to the right side compared with the width of the text body underneath, so to correct this I actually ended up using:

\newcommand{\mysubsection}[1]{
    \setlength\fboxsep{4pt} %% spacing around box contents
    \subsection*{\colorbox{bgcol}{\makebox[0.97\textwidth]{\color{textcol}#1}}}
}

Caution: I am getting error messages from "Overfull \hbox" using this code. I don't know how to resolve this, but the output is working fine so it is not an issue for me. On a different program or build this may cause you problems!

like image 28
Scott Lowe Avatar answered Mar 23 '23 15:03

Scott Lowe