# The simplest way to fill a matrix of nodes?

Code:

           \tikzstyle{matrici}=[
matrix of math nodes,
nodes in empty cells,
column sep=-\pgflinewidth, % to avoid double borders in contiguous cells
nodes={
draw,
align=center,
inner sep=0pt,
text width=1cm,
minimum height=1cm
}
]

\begin{tikzpicture}
\matrix[matrici,
column 1/.style={nodes={fill=blue!10}},
column 2/.style={nodes={fill=blue!10}},
column 3/.style={nodes={fill=blue!10}},
column 4/.style={nodes={fill=blue!10}},
]  (X)  {&&&&&&&\\};
\end{tikzpicture}


output: there is no way ti fill the first 4 cells with a "cicle for"? Im forced to write this?

   column 1/.style={nodes={fill=blue!10}},
column 2/.style={nodes={fill=blue!10}},
column 3/.style={nodes={fill=blue!10}},
column 4/.style={nodes={fill=blue!10}},


it will be fine somethig like

   \foreach \x in {1,2,3,4}
fill the node (X-1-\x) with this color


## 2 Answers

You can do add a \fill to the background layer: \documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix,backgrounds}
\tikzset{ % \tikzstyle is considered deprecated
matrici/.style={
matrix of math nodes,
nodes in empty cells,
column sep=-\pgflinewidth, % to avoid double borders in contiguous cells
nodes={
draw,
align=center,
inner sep=0pt,
text width=1cm,
minimum height=1cm
}
}
}

\begin{document}
\begin{tikzpicture}
\matrix[matrici]  (X)  {&&&&&&&\\};

\begin{scope}[on background layer]
\foreach \x in {1,...,4}
\fill [blue!10] (X-1-\x.south west) rectangle (X-1-\x.north east);
\end{scope}
\end{tikzpicture}

\end{document}


Another option is to do something similar to what Loop Space did in his answer to How can I set the background color of the rows and columns of a matrix node in Tikz?:

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix,backgrounds}
\tikzset{
matrici/.style={
matrix of math nodes,
nodes in empty cells,
column sep=-\pgflinewidth, % to avoid double borders in contiguous cells
nodes={
draw,
align=center,
inner sep=0pt,
text width=1cm,
minimum height=1cm
}
}
}

\begin{document}
\begin{tikzpicture}
\matrix[
matrici,
nodes={
execute at begin node={
\pgfmathparse{\pgfmatrixcurrentcolumn<5 ? "blue!10" : "white"}
\xglobal\colorlet{nodebg}{\pgfmathresult}},
preaction={fill=nodebg}
}
]  (X)  {&&&&&&&\\};

\end{tikzpicture}
\end{document}


Pardon my ignorance of understanding your question but if you are looking for creating a colored box then you can do the following (i.e. please correct me if I misunderstood your question because it is not totally clear to me).

\documentclass[border={10pt}]{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
colorbox/.style={rectangle,fill=blue!10,draw=black,thick, minimum size=1cm},
box/.style={rectangle,draw=black,thick, minimum size=1cm},
]%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\foreach \x in {0,...,3}
\node[colorbox] at (\x,0){};

\foreach \x in {4,...,7}
\node[box] at (\x,0){};

\end{tikzpicture}
\end{document} 