How to set the fixed width of columns?

neo33 picture neo33 · May 23, 2016 · Viewed 67.3k times · Source

Hello everyone I am creating a table on latex my code looks like this:

\begin{table}[H]
\centering
\caption{caption}
\label{my-label}
\begin{tabular}{lll}
\hline
\multicolumn{3}{|c|}{\cellcolor[HTML]{34CDF9}{\color[HTML]{000000} Matriz confusión  Genero.}} \\ \hline
\multicolumn{1}{|l|}{}        & \multicolumn{1}{l|}{M}       & \multicolumn{1}{l|}{F}        \\ \hline        
\multicolumn{1}{|l|}{M}        & \multicolumn{1}{l|}{43}       & \multicolumn{1}{l|}{7}        \\ \hline
\multicolumn{1}{|l|}{F}        & \multicolumn{1}{l|}{11}       & \multicolumn{1}{l|}{39}       \\ \hline
\end{tabular}
\end{table}

It works well but the problem comes when I try to fix the width of the columns I tried:

\begin{tabular}{l{2cm}|l{2cm}|l{2cm}}

The result is the same table, with variable length of columns, I would like to fix the length of the columns, I would like to appreciate any suggestion to solve this problem.

Answer

MattAllegro picture MattAllegro · May 23, 2016

Consider the following code:

\documentclass[a4paper]{article}
\usepackage{}

\begin{document}

\begin{table}%[H]
    \centering
    \caption{caption}
    \label{my-label}
    \begin{tabular}{|p{20mm}|p{15mm}|p{10mm}|}
        \hline
%       \multicolumn{3}{|c|}{\cellcolor[HTML]{34CDF9}{\color[HTML]{000000} Matriz confusión  Genero.}} \\ \hline
        \multicolumn{3}{|c|}{Matriz confusión  Genero.} \\ \hline
         & M & F \\ \hline
         M & 43 & 7 \\ \hline
         F & 11 & 39 \\ \hline
    \end{tabular}
\end{table}

\end{document}

that outputs the following table:

screenshot of output

You may be interested in particular in the line

\begin{tabular}{|p{20mm}|p{15mm}|p{10mm}|}

implementing paragraph alignment for the contents of a column of given width (here 20, 15 and 10 mm respectively).


To make it simpler, you should just get rid of all of those \multicolumn{1}{}{} and change

\begin{tabular}{l{2cm}|l{2cm}|l{2cm}}

to

\begin{tabular}{|p{2cm}|p{2cm}|p{2cm}|}