我有一个带有背景色的框内的标题。我的问题是我需要将框的宽度对齐以使其等于表格宽度。
电流输出
我的代码:
\documentclass{article}
\usepackage{lipsum,graphicx,xcolor,caption,tabulary}
\newcommand{\captionbackgroundcolor}[1]{\colorlet{cpbgcol}{#1}}
\DeclareCaptionFont{white}{\color{white}}
\captionbackgroundcolor{black!50}
\DeclareCaptionFormat{overlay}{\colorbox{cpbgcol}{#1#2#3}}
\captionsetup{format=overlay,font=white}
\begin{document}
\lipsum[1]
\begin{table*}[!htbp]
\caption{{Categor\'{\i}as y variables de la primera muestra} }
\label{tw-592d6b646c21}
\def\arraystretch{1.2}
\ignorespaces
\centering
\begin{tabulary}{\linewidth}{|L|L|}
\hline
samlple &sample\\
sample & sample\\
\hline
\end{tabulary}\par
\end{table*}
\lipsum[2]
\end{document}
答案1
我修改了您的一些标签,请检查并确认是否满足您的要求:
\documentclass{article}
\usepackage{xcolor,caption,threeparttable,booktabs}
\newcommand{\captionbackgroundcolor}[1]{\colorlet{cpbgcol}{#1}}
\DeclareCaptionFont{white}{\color{white}}
\captionbackgroundcolor{black!50}
%\DeclareCaptionFormat{overlay}{\colorbox{cpbgcol}{#1#2#3}}
%\captionsetup{format=overlay,font=white}
\begin{document}
\makeatletter
\long\def\@tablecaption#1#2{\colorbox{black!10}{\vbox{\fontsize{9.5}{10}\selectfont%
{\bfseries #1}\hspace{1em}{#2\strut}\par}}
\vspace{\belowcaptionskip}}
\def\table{\let\@makecaption\@tablecaption\@float{table}}
\let\endtable\end@float
\makeatother
\begin{table}
\centering
\begin{threeparttable}
\caption{This is example
table with width equal to default width in table environment}
\begin{tabular}{|c|c|c|c|}
\hline
Col 1& Col 2 & Col 3 & Col 4 \\
\hline
1 & 2 & 3 & 4 \\
5 & 6 & 7 & 8 \\
9 & 10 & 11 & 12 \\
\hline
\end{tabular}
\begin{tablenotes}[flushleft]\footnotesize
\item[1] Long, long, long, long, long, long, note
\end{tablenotes}
\end{threeparttable}
\end{table}
\end{document}
答案2
由于标题通常填满整个页面宽度,因此将标题放入框内的最佳方法是使用 minipage(或修改\@makecaption
)。同样,\colorbox
不会换行,因此您需要一个\parbox
inside。
请注意,在所有侧面 \colorbox
都增加了间隙。在每个列单元格的侧面都增加了间隙。\fboxsep
\tabulary
\tabcolsep
\documentclass{article}
\usepackage{lipsum,graphicx,xcolor,caption,tabulary}
\newcommand{\captionbackgroundcolor}[1]{\colorlet{cpbgcol}{#1}}
\DeclareCaptionFont{white}{\color{white}}
\captionbackgroundcolor{black!50}
\DeclareCaptionFormat{overlay}{\colorbox{cpbgcol}{\parbox{\dimexpr \textwidth-2\fboxsep}%
{\centering#1#2#3}}}
\captionsetup{format=overlay,font=white}
\begin{document}
\lipsum[1]
\begin{table*}[!htbp]
\centering
\def\arraystretch{1.2}%
\begin{tabulary}{\linewidth}{|L|L|}
\hline
\multicolumn{2}{|c|}{\begin{minipage}{2in}% arbitrary width
\abovecaptionskip=\tabcolsep
\belowcaptionskip=\tabcolsep
\caption{Categor\'{\i}as y variables de la primera muestra}%
\label{tw-592d6b646c21}%
\end{minipage}}\\
\hline
samlple &sample\\
sample & sample\\
\hline
\end{tabulary}
\par
\end{table*}
\lipsum[2]
\end{document}