# TikZ: put caption into a node

I would like to put the caption of my figure into my node, something like

\usepackage{tikz}
\usepackage{subcaption}

\begin{figure}
\begin{subfigure}[t]{\textwidth}
\begin{tikzpicture}
\draw (0,0) node {\caption{This is the caption}\label{fig}};
\end{tikzpicture}
\end{subfigure}
\end{figure}


Is there any possibility to do this?

just define text width for node:

\documentclass{article}
\usepackage{tikz}
\usepackage{subcaption}

\begin{document}
\begin{figure}
\begin{subfigure}[t]{\textwidth}
\begin{tikzpicture}
\draw (0,0) node[text width=\linewidth] {\caption{This is the caption}\label{fig}};
\end{tikzpicture}
\end{subfigure}
\end{figure}


note: caption can be only in text or in environments which support writting paragraph as are parbox, minipage, ...

if you define text width of node, than node's content has paragraph features

addendum an example for more fancy looks of node:

\documentclass{article}
\usepackage{tikz}
\usepackage{subcaption}

%--- show page layout, only for test, don't use in real document!
\usepackage{showframe}
\renewcommand\ShowFrameLinethickness{0.15pt}
\renewcommand*\ShowFrameColor{\color{red}}
%---------------------------------------------------------------%

\begin{document}
\begin{figure}
\begin{subfigure}[t]{\textwidth}
\begin{tikzpicture}
\draw (0,0) node[
draw=yellow!60,                 % border around node with defined color
semithick,                      % border line thicknes
fill=yellow!30,                 % color of node's fill
text width=\linewidth-          % with  of node,
% considered are inner xsep
% and shadow xhift, with this it
% not spill out right text border
2*\pgfkeysvalueof{/pgf/inner xsep}-4pt,
text=black,                     % text color
% color of the fill
%% default values are:
shadow xshift= 4pt, % shift to the right
shadow yshift=-4pt} % shift down (or with sign - up)
] {\caption{This is the caption}\label{fig}};
\end{tikzpicture}
\end{subfigure}
\end{figure}
\end{document}


for even more fancy styles you should consider package tcolorbox.

• Thanks for this brilliantly simple solution. I have no idea how people are able to figure out what is wrong, for me Latex errors are unreadable. There is just one slight issue, I would like to put a white background (or sometimes a box) around the text. Giving the additional option node[..., fill=white] now fills the whole text width. Is there a better solution than adding another node displaying phantom text to draw the background? Mar 10, 2018 at 9:42

After trying for an hour I couldn't figure it out, 5 minutes later I come up with a solution... Nevertheless here it is:

\usepackage{tikz}
\usepackage{subcaption}

\newcommand{\nodecaption}[2]{\subcaptionbox{#1\label{#2}}{\phantom{(X)~#1}}}

\begin{figure}
\begin{subfigure}[t]{\textwidth}
\begin{tikzpicture}
\draw (0,0) node {\nodecaption{This is the caption}{fig}};
\end{tikzpicture}
\end{subfigure}
\end{figure}


Far from optimal but it does the job.