[Tex/LaTex] Table inside a fcolorbox

tables

Here is what I am trying to do:

I am trying to create an environment similar to a colored textboxin MS Word and enter text, table, and formulas inside the box. Right now, this is what I do:

  \fcolorbox{black}{black!20}{\parbox{\textwidth}{%
        \color{red!70!black}%
text text math math
    }}

However, when I try to include a table inside this environment, I get error. Is it possible to modify this environment such that it can also accommodate the tables as well?

Here is a MWE:

\documentclass[12pt, xcolor=pdftex,x11names,table]{article}
\usepackage{tabularx}
\usepackage{graphicx}
\usepackage{mathtools}

\usepackage{pdfpages}
\usepackage{setspace}
\usepackage{verbatim}
\usepackage{subfig}
\begin{document}
text $i=j$ 


      \fcolorbox{black}{black!20}{\parbox{\textwidth}{%
            \color{red!50!black}%
again text and $math$
\begin{table}
    \begin{tabular}{ccc}

      \textbf{Q} & \textbf{test}&\textbf{test2}\\
      \hline
      5 &&\\
      \hline
      \end{tabular}%

\end{table}
        }}
\end{document}

Best Answer

You cannot embed (or contain) a float inside a box (\parbox or minipage, say). Moreover, you don't need the table (float) environment in order to set a tabular. So you could just get by with the following:

enter image description here

\documentclass{article}
\usepackage{xcolor,tabularx}% http://ctan.org/pkg/{xcolor,tabularx}
\begin{document}
text $i=j$ 

\noindent
\fcolorbox{black}{black!20}{\parbox{\dimexpr\textwidth-2\fboxsep-2\fboxrule}{%
  \color{red!50!black}%
  again text and $math$
    \begin{tabular}{ccc}
      \textbf{Q} & \textbf{test}&\textbf{test2}\\
      \hline
      5 &&\\
      \hline
    \end{tabular}%
}}
\end{document}

Note that using a \parbox of width \textwidth inside a \fcolorbox will cause an overfull \hbox. That is because the \fcolorbox adds some separation (\fboxsep on both sides) and a rule (of width \fboxrule, on both sides). I've accommodated for this using

\dimexpr\textwidth-2\fboxsep-2\fboxrule

as the width of the \parbox.

Related Question