titlesec:计算部分标题背景的正确宽度

titlesec:计算部分标题背景的正确宽度

我正在titlesec使用将章节编号放在左边距以及应用横跨页面宽度的阴影背景

我现在也在使用wrapfig,有些章节标题被包裹在数字周围。我该如何调整我的定义,\colorsection以便背景仅延伸到右边距,而不是超出它?

在此处输入图片描述

\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}

答案1

只需在定义中替换\textwidth为:\linewidth\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} 

在此处输入图片描述

相关内容