2

I've defined the following command that just draws four colored rectangles with some text inside them:

\newcommand{\fourcards}[4]{
    \begin{figure}
        \centering
        \begin{tabular}{cccc}
            \centering
            \tikz \draw[fill=green!50] (0,0) rectangle (1,1) node[pos=.5] {#1}; &
             \tikz \draw[fill=magenta] (0, 0) rectangle(1, 1) node[pos=.5]{#2}; & 
            \tikz \draw[fill=orange] (0, 0) rectangle(1, 1) node[pos=.5]{#3}; & 
            \tikz \draw[fill=yellow] (0, 0) rectangle(1, 1) node[pos=.5]{#4};
        \end{tabular}   
    \end{figure}
}

I was wondering if there was some way to change the dimensions of the rectangles dynamically, such that they accommodate the text inside them. I have found this thread discussing something similar, but the OP there requires that the rectangle follows constraints imposed outside the rectangle: I want the rectangle to adjust itself to constraints inside it.

1
  • you could use a tabular for this
    – Runar
    Jun 27, 2016 at 15:12

1 Answer 1

4

That's what a node does, and it can have a fill. What's the purpose of the figure environment?

\documentclass{article}
\usepackage{tikz}
\newcommand{\fourcards}[4]{%
    \begin{figure}
        \centering
        \begin{tabular}{cccc}
            \tikz \node[draw,fill=green!50] {#1}; &
             \tikz \node[draw,fill=magenta] {#2}; & 
            \tikz \node[draw,fill=orange] {#3}; & 
            \tikz \node[draw,fill=yellow] {#4};
        \end{tabular}   
    \end{figure}%
}
\begin{document}
\fourcards{TexT}{Lorem upsum}{Whatnot}{woooooooord}
\end{document}

Slightly different approach:

\documentclass{article}
\usepackage{tikz}
\newcommand{\fourcards}[4]{%
\begin{tikzpicture}[every node/.append style={text depth=3pt,text height=10pt}]
\matrix [ampersand replacement=\&,column sep=5pt] {
\node[draw,fill=green!50] {#1}; \&
\node[draw,fill=magenta] {#2}; \& 
\node[draw,fill=orange] {#3}; \& 
\node[draw,fill=yellow] {#4}; \\
};
\end{tikzpicture}}
\begin{document}
\fourcards{TexT}{Lorem upsum}{Whatnot}{woooooooord}
\end{document}
1
  • Ah, that worked famously, thanks. The only reason for me to use the figure environment is because I needed an enveloping float for the tabular environment to control the placement better. It could've been a table instead.
    – Jason
    Jun 27, 2016 at 15:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .