标题宽度大于列表宽度

标题宽度大于列表宽度

考虑以下最小工作示例这里

\documentclass{report}

\usepackage{color}
\usepackage{xcolor}
\usepackage{listings}

\usepackage{caption}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}

% This concludes the preamble

\begin{document}

\begin{lstlisting}[label=some-code,caption=Some Code]
public void here() {
    goes().the().code()
}
\end{lstlisting}

\end{document}

我希望列表的背景是灰色,所以我添加了

\lstset{                                                                        
     backgroundcolor=\color{gray!10},                                        
} 

到序言部分。结果如下:

如您所见,标题比列表宽。如何使标题与列表一样宽?

答案1

A在其左侧和右侧\colorbox插入间距,因此右侧长度为,这意味着您必须声明\fboxsep\linewidth-2\fboxsep

\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\dimexpr\linewidth-2\fboxsep\relax}{#1#2#3}}}

梅威瑟:

\documentclass{report}

\usepackage{color}
\usepackage{xcolor}
\usepackage{listings}

\lstset{
     backgroundcolor=\color{gray!10},
} 

\usepackage{caption}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\dimexpr\linewidth-2\fboxsep\relax}{#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}

% This concludes the preamble

\begin{document}

\begin{lstlisting}[label=some-code,caption=Some Code]
public void here() {
    goes().the().code()
}
\end{lstlisting}

\end{document} 

输出:

在此处输入图片描述

相关内容