[Tex/LaTex] How to caption/subcaption a tabular? easily

captionssubcaption

I few week ago, I learned subcaption figuras, with subcaption packages, and I like it very much.

Now I would like to caption/subcaption tabulars.

I was vieweing any issues and all have a table enviroment OVER the \begin{tabular} \end{tabular}

What´s the best and easy way to caption/subcaption a tabular??

like this….

\documentclass[12pt,a4paper,x11names]{article}
\usepackage[top=2.5cm, left=3.5cm, bottom=2.5cm, right=2.5cm]{geometry}

\usepackage{lipsum,mwe}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[spanish]{babel}

\begin{document}
Hello,\\

\begin{tabular}{|c|c|r|}
  \hline
  % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
  a & e & 12 \\
  \hline
  f & g & 3 \\
  \hline
\end{tabular}

\end{document}

Best Answer

Repeating the suggestions provided in the comments: Place the existing tabular environment inside a table environment. It is common -- though not mandatory -- to center the material inside a table environment. The command \centering achieves that objective. The table and figure environments are "floats", i.e., unless you explicitly instruct LaTeX not to do so, LaTeX will place them where it thinks it's best. For much more on floats and the LaTeX algorithm that determines float placement, see the posting How to influence the position of float environments like figure and table in LaTeX?

The table environment can be given a \caption and a \label. Assigning labels is useful if you want to cross-reference the table somewhere else in your document using the TeX/LaTeX command \ref.

If you do a lot of cross-referencing -- not only to tables, but to sections, figures, page numbers, etc -- you may want to get to know the cleveref package and its command \cref. For more on LaTeX's cross-referencing mechanisms and packages that provide enhanced cross-referencing macros see the posting Cross-reference packages: which to use, which conflict?

Here, finally, is your tabular environment encased in a table environment, with a couple of cross-referencing commands thrown in for good measure.

enter image description here

\documentclass[12pt,a4paper,x11names]{article}
\usepackage[vmargin=2.5cm, left=3.5cm, right=2.5cm] {geometry}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[spanish]{babel}
\usepackage[spanish]{cleveref} %% new

\begin{document}
Hello, \dots

\begin{table}[h]  %% new
\centering        %% new
\caption{A simple table} %% new
\label{tab:simple}       %% new
\begin{tabular}{|c|c|r|}
  \hline
  % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
  a & e & 12 \\
  \hline
  f & g & 3 \\
  \hline
\end{tabular}
\end{table} %% new

Here's a cross-reference to table \ref{tab:simple}.  %% new

Here's a cross-reference to \cref{tab:simple}.  %% new
\end{document}