[Tex/LaTex] specified column width

tableswidth

I'm using the following code for the table. Currently it is set up so that I can change the width of all column (except the first one) to the same width. Can someone help me tweet it so that I can specify the column width every time I use it? Thank you.

\documentclass[twoside]{book}

\usepackage{tikz}
%%table 
\usetikzlibrary{matrix}
\tikzset{ 
    table/.style={
        matrix of nodes,
        row sep=-\pgflinewidth,
        column sep=-\pgflinewidth,
        nodes={
            rectangle,
            draw=gray!50,
            align=center
        },
        minimum height=1.5em,
        text depth=0.5ex,
        text height=2ex,
        nodes in empty cells,
%%
        every odd row/.style={
            nodes={fill=gray!05}
        },
        column 1/.style={
          nodes={text width=5em,font=\bfseries}
        },
        row 1/.style={
            nodes={
                fill=gray!25,
                text=black,
                text height=2.5ex,
                font=\bfseries, purple!75!black
            }
        }
    }
}

\begin{document}

\begin{tikzpicture}
\matrix[table,text width=12em]
{
first & 2nd column   & 3rd column\\
&A & B \\
& C & D \\
};
\end{tikzpicture}

\end{document}

I want to put this in the preamble, but that means I have to have the all the tables in the same document to the same width specified, as of now.

Thank you.

Best Answer

Do you want something like this so that you can adjust the width of the first column as well as that of the other columns?

\documentclass{book}
\usepackage{tikz}
\usetikzlibrary{matrix}
\tikzset{
  table/.style={
    matrix of nodes,
    row sep=-\pgflinewidth,
    column sep=-\pgflinewidth,
    nodes={
      rectangle,
      draw=gray!50,
      align=center
    },
    minimum height=1.5em,
    text depth=0.5ex,
    text height=2ex,
    nodes in empty cells,
    %%
    every odd row/.style={
      nodes={fill=gray!05}
    },
    first column text width/.code={%
      \tikzset{
        column 1/.style={
          nodes={text width=##1, font=\bfseries}
        },
      }
    },
    first column text width=5em,
    row 1/.style={
      nodes={
        fill=gray!25,
        text=black,
        text height=2.5ex,
        font=\bfseries, purple!75!black
      }
    }
  }
}
\begin{document}

  \begin{tikzpicture}
    \matrix[table,text width=12em]
    {
      first & 2nd column   & 3rd column\\
      &A & B \\
      & C & D \\
    };
  \end{tikzpicture}

  \begin{tikzpicture}
    \matrix[table,text width=6em, first column text width=3em]
    {
      first & 2nd column   & 3rd column\\
      &A & B \\
      & C & D \\
    };
  \end{tikzpicture}
\end{document}

variant tables

Related Question