# tikz matrix background color for unevenly sized cells

I've adapted the example below from elsewhere on this forum. What I'd like is to have the background fill to come out as a rectangle covering the contents of all cells. What is the easiest way to accomplish that automatically in tikz, i.e. in such a way that the code works regardless of the cell contents? (I know how to fudge things manually using minimum width, \vphantom and the like, but I'm looking for something automatic in tikz.)

Thanks!

\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{arrows,matrix,positioning}
\begin{document}
\begin{tikzpicture}
\matrix [matrix of math nodes,left delimiter=(,right delimiter=)] (m)
{
8 &8 & \dfrac{1}{5} &6 \\
\text{three} &\dfrac{8}{3} &5 &7 \\
4 &8 &9 &5 \\
};
\draw[fill=pink,opacity=0.2] (m-1-1.north west) -- (m-1-3.north east) -- (m-2-3.south east) -- (m-2-1.south west) -- (m-1-1.north west);
\end{tikzpicture}
\end{document}


Instead to draw line arround nodes try to use rectangle shape, which fit this nodes:

\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{backgrounds,fit,matrix,positioning}
%%%% se-prewiew-tikz
\usepackage[active,floats,tightpage]{preview}
\PreviewEnvironment{tikzpicture}% <---------------------------------
\setlength\PreviewBorder{1em}

\begin{document}
\begin{tikzpicture}
\matrix [matrix of math nodes,left delimiter=(,right delimiter=)] (m)
{
8   &   8               &   \dfrac{1}{5}    &   6   \\
\text{three}   &   \dfrac{8}{3}    &           5       &   7   \\
4   &   8               &           9       &   5   \\
};
\scoped[on background layer]
\node[fill=pink!50,inner xsep=0mm, yshift=-1mm,
fit=(m-1-1) (m-1-3) (m-2-3) (m-2-1) (m-1-1)]   {};
\end{tikzpicture}
\end{document}


• Thanks; had to upgrade to pgf 3.0, but for that it works! – JPi Jan 4 '15 at 21:44
• @Zarko This is a nice solution but you must be sure to include all nodes which are relevant for final rectangle size, i.e. the most width nodes in left and right columns and the taller nodes in top and bottom rows. In the example (m-2-2) is missing and should be there. In this case with (m-1-3) (m-2-1) (m-2-3) would be enough. – Ignasi Jan 7 '15 at 16:04