[Tex/LaTex] Box around tikz-cd diagram, without ampersand replacement

ampersandtikz-cd

Problem statement:

I'd like to put a box around a tikz-cd diagram, without needing to use ampersand replacement. Using \fbox seems to require ampersand replacement.

Demonstration:

The following gives an error:

\documentclass{article}
\usepackage{tikz-cd}

\begin{document}

\[
\fbox{
  \begin{tikzcd}       %error: must use ampersand replacement
    A \ar[r, "f"] & B
  \end{tikzcd}
}
\]

\end{document}

The following works:

\documentclass{article}
\usepackage{tikz-cd}

\begin{document}

\[
\fbox{
  \begin{tikzcd}[ampersand replacement = \&]
    A \ar[r, "f"] \& B
  \end{tikzcd}
}
\]

\end{document}

Complaint:

It is annoying to have to use ampersand replacement every time I want a box!

Question: Is there another way to draw a box around a tikz-cd diagram that does not cause the ampersand problem? More generally, is there a way to embed a tikzcd diagram as a node in a tikz picture?

Thanks!

Best Answer

You can try the following:

\documentclass{article}
\usepackage{tikz-cd}

\begin{document}

\begin{tikzpicture}[mybox/.style={draw, inner sep=5pt}]
\node[mybox] (box){%
  \begin{tikzcd}
    A \ar[r, "f"] & B
  \end{tikzcd}
};
\end{tikzpicture}

\end{document}

enter image description here

You can adjust the inner sep in mybox and/or add options such as thick, rounded corners, fill=, draw= etc. for different style boxes. For example,

[mybox/.style={draw=blue, fill=yellow!50, very thick, rounded corners,
    inner sep=5pt}]

will produce

enter image description here

Related Question