# titlesec: calculate correct width for section heading background

I’m using titlesec to place section numbers in the left margin and also to apply a shaded background that spans the width of the page.

I’m now also using wrapfig, and some section headings are being wrapped around figures. How do I adjust my definition of \colorsection so that the background extends only to the right margin, rather than beyond it?

\documentclass{article}
\usepackage{titlesec}
\usepackage{mwe}
\usepackage{wrapfig}
\usepackage{graphicx}
\usepackage{xcolor}

% https://tex.stackexchange.com/questions/40034
\newcommand{\colorsection}[1]{\colorbox{blue!20}{\parbox[t]{\dimexpr\textwidth-2\fboxsep}{#1}}}
% https://tex.stackexchange.com/questions/523000
\newcommand*{\marginsecnumber}[1]{\makebox[0pt][r]{#1\hspace{6pt}}}

\titleformat{\section}{\Large\bfseries}{\marginsecnumber\thesection}{0em}{\colorsection}

\begin{document}
\section{Section}
\begin{wrapfigure}{l}{2.5in}
\includegraphics[scale=0.5]{example-image-a}
\end{wrapfigure}
Here's some example text, not too much.
\section{Another section}
\end{document}


Simply replace \textwidth with \linewidth in the dfinition of \colorsection:

\documentclass{article}
\usepackage{titlesec}
\usepackage{showframe}
\renewcommand{\ShowFrameLinethickness}{0.3pt}
\usepackage{mwe}
\usepackage{wrapfig}
\usepackage{graphicx}
\usepackage{xcolor}

% https://tex.stackexchange.com/questions/40034
\newcommand{\colorsection}[1]{\colorbox{blue!20}{\parbox[t]{\dimexpr\linewidth-2\fboxsep}{#1}}}
%
% https://tex.stackexchange.com/questions/523000
\newcommand*{\marginsecnumber}[1]{\makebox[0pt][r]{#1\hspace{6pt}}}

\titleformat{\section}{\Large\bfseries}{\marginsecnumber\thesection}{0em}{\colorsection}

\begin{document}

\section{Section}
\begin{wrapfigure}{l}{2.5in}
\includegraphics[scale=0.5]{example-image-a}
\end{wrapfigure}
Here's some example text, not too much.
\section{Another section}

\end{document}


• Perfect, thanks! – Roly Jan 6 at 19:44