[Tex/LaTex] “Can’t use \vadjust in internal vertical mode” triggered by two-line hanging caption, using adjustbox, caption packages

adjustboxcaptions

I want: a floating table with caption (with hanging indent), such that both the table and caption are surrounded by a frame filled with a background color.

enter image description here

My environment hierarchy is table » adjust box » \caption » tabular.

I'm using the caption package to format captions, crucially here with the format=hang option.

In the following MWE, the \caption command triggers a

You can't use '\vadjust' in internal vertical mode

error, but this disappears if any of the following:

  • I shorten the caption text so that it doesn't flow to a second line.
  • I remove the format=hang option from \captionsetup

Why does this occur? (I have no idea where \vadjust is occurring or why it's throwing an error.)

Or, more generally, an alternative solution that allows both (a) the colored frame surrounding the table and caption and (b) hanging indent for the caption?

I realize that I could dispense with the explicit table environment and let the adjustbox environment (a) float a table and (b) format the caption. The problem is that my colored frame would then not include the caption (because, per the adjust box docs, §4.13, keys used to turn an adjusted box into a float "which also allows for a caption… must be used last and no other normal keys must be used again afterwards, otherwise an error will occur because the added floating environment is boxed again").

\documentclass[12pt]{article}
\usepackage{adjustbox}
\usepackage{xcolor}
\usepackage{caption}
\captionsetup{margin=2em, labelfont={bf},format=hang,justification=raggedright}
\begin{document}
\begin{table}
    \begin{adjustbox}{varwidth=\textwidth,padding=1em,bgcolor=pink,frame=1pt,center}
        \caption{A caption designed to be long enough that it flows to the next line}
        \begin{tabular}[t]{cc}
            Column1 & Column2 \\
            \hline
            $x$ & $y$ \\
        \end{tabular}
    \end{adjustbox}
\end{table}
\end{document}

Best Answer

Why not a minipage?

\documentclass[12pt]{article}
\usepackage{adjustbox}
\usepackage{xcolor}
\usepackage{caption}

\captionsetup{margin=2em, labelfont={bf},format=hang,justification=raggedright}

\begin{document}

\begin{table}
\begin{adjustbox}{padding=1em,bgcolor=pink,frame=1pt,center}
\begin{minipage}{\dimexpr\textwidth-1pt-1em}
  \caption{A caption designed to be long enough that it flows to the next line}
  \begin{tabular}[t]{cc}
  Column1 & Column2 \\
  \hline
  $x$ & $y$ \\
  \end{tabular}
\end{minipage}
\end{adjustbox}
\end{table}

\end{document}

enter image description here