Skip to content
ImagineWorld

Creating Tables

node_idnode-book_latex-beginner-s-guide_chapter-05-creating-tables
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleCreating Tables
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Scientific and technical documents often contain more than plain text; they also include structured data. In the previous chapter, we looked at ways to organize information with different kinds of lists and how to customize their layout. Now, we will turn to presenting data in tables.

We’ll cover the following topics:

  • Aligning text with tab stops
  • Creating basic tables
  • Improving table appearance
  • Adding captions to tables
  • Enhancing tables with additional packages

We’ll start by simply arranging text in columns.

Do you remember using tab stops on typewriters or in early word processing software for creating aligned columns of text? LaTeX offers a similar mechanism with the tabbing environment to neatly align text in columns.

Let’s create a compact overview of LaTeX. We’ll display one item per line, aligning key parts of the text, using the following steps:

  1. Begin a new document and open a tabbing environment:
    \documentclass{article}
    \begin{document}
    \begin{tabbing}
  2. Write the first line of text. Use \= to set tab stops and \\ to end the line:
    \emph{Info:} \= Software \= : \= \LaTeX \\
  3. Add more lines; use \> to jump to the next tab stop and again end the line with \\:
    \> Author \> : \> Leslie Lamport \\
    \> Website \> : \> www.latex-project.org
  4. Close the tabbing environment and end the document:
    \end{tabbing}
    \end{document}
  5. Click the Typeset button to compile the document, and take a look at the output:

Figure 5.1 – Simply aligned text

Figure 5.1 – Simply aligned text

The tabbing environment automatically starts a new line. We used three basic commands to control alignment:

  • \= sets a tab stop. You can place multiple tab stops on a single line. We typically do that in the first row.
  • \\ ends a row.
  • \> jumps to the next defined tab stop.

While tab stops are usually set in the first row, you can also redefine them in later lines using \=. For instance, if we already used two \> commands in a text line to navigate through two tab stops, inserting another \= command sets or adjusts a third tab stop on that line.

At https://latexguide.org/tabbing, you can see several examples using these tags.

The tabbing environment provides a quick way to create left-aligned columns. If the rows of the tabbing environment reached the end of a page, it would automatically continue on the next page. That makes it a basic yet efficient way to create tables that cross page breaks or even span multiple pages.

But what happens if the text exceeds the width and runs over the tab stop? Let’s see how to handle that next.

In Chapter 2, Formatting Text and Creating Macros, we explored various font commands and declarations. You may recall a table that listed these commands alongside their output. Let’s now create such a table ourselves, as follows:

  1. Begin a new document, similar to step 1 of our previous example, but this time, define a command for setting the header text in bold:
    \documentclass{article}
    \newcommand{\head}[1]{\textbf{#1}}
    \begin{document}
    \begin{tabbing}
  2. Define tab stops in the first row using \= and use \> to jump to tab stops. Use the \verb|…| command you learned about in the previous chapter to display LaTeX code verbatim:
    \= \head{Command} \= \head{Declaration} \= \head{Example}\\
    \> \verb|\textrm{...}| \> \verb|\rmfamily| \> \rmfamily text\\
    \> \verb|\textsf{...}| \> \verb|\sffamily| \> \sffamily text\\
    \> \verb|\texttt{...}| \> \verb|\ttfamily| \> \ttfamily text
  3. End the tabbing environment and the document:
    \end{tabbing}
    \end{document}
  4. Compile the document and examine the output:

Figure 5.2 – Overlapping aligned text

Figure 5.2 – Overlapping aligned text

  1. As we can see, the tab stops are too narrow at this point, causing the columns to overlap. We shall correct it. Create a new head row containing the tab stops, but this time, we will end the line with \kill to hide that line. Use filler text to specify the width between the tab stops, such as the longest text in the column. Complete it with further font commands. The tabbing code now looks like this:
    \begin{tabbing}
    \= \verb|\textrm{...}| \= \head{Declaration} \=
    \head{Example}\kill
    \> \head{Command} \> \head{Declaration} \> \head{Example}\\
    \> \verb|\textrm{...}| \> \verb|\rmfamily| \> \rmfamily text\\
    \> \verb|\textsf{...}| \> \verb|\sffamily| \> \sffamily text\\
    \> \verb|\texttt{...}| \> \verb|\ttfamily| \> \ttfamily text
    \end{tabbing}
  2. Compile again to get the final result:

Figure 5.3 – Corrected aligned text

Figure 5.3 – Corrected aligned text

After realizing that our tab stops were too narrow, we added a new first row containing the tab stops. It consists of words representing the widest entries of each column. To keep this additional row from appearing in the output, we used the \kill command right at the end of the line; \kill at the end of a line skips printing the line but still registers the tab stops.

There are further useful commands that are handy if you frequently work with tabbed texts:

  • \+ at the end of a line (before \\) moves the left margin of the subsequent lines one tab stop to the right. Use it twice, \+\+, to move it two tab stops to the right, and so on.
  • \- at the end of a line moves the left margin of the subsequent lines one tab stop to the left. Also, here, \-\- would move two tab stops to the left. \- is basically for canceling the effect of a previous indentation made by a prior \+ command.
  • \< cancels the effect of a preceding \+ command for that line. It moves the left margin one tab stop to the left. We should only use it at the beginning of a line. Repeat it to move two tab stops to the left.

These commands give you solid control over the tabbing environment. For a full list of features, check the reference manual: https://latex2e.org/tabbing.

Inside a tabbing environment, declarations are local to the current item. A following \=, \>, \\, or \kill command would stop the effect.

Also, tabbing environments cannot be nested.

That wraps up how to align text in columns in a quick way. Next, let’s see how to build tables with alignment and separation lines.

Sometimes we need more complex structures and formatting, such as centering within columns, inserting horizontal dividing lines, or even creating nested structures. LaTeX provides the tabular environment for building both simple and complex tables.

Let’s recreate the table of font family commands from our previous example, this time with centered columns. We will also add some horizontal lines to visualize the table’s border and the header. Follow these steps:

  1. Create a new document. Define a command for setting the font for the head row:
    \documentclass{article}
    \newcommand{\head}[1]{\textnormal{\textbf{#1}}}
    \begin{document}
  2. Begin a tabular environment. As a mandatory argument, provide ccc, standing for three centered columns:
    \begin{tabular}{ccc}
  3. Write the table head row, use the & character to separate column entries, and finish with \\ to end rows. Use \hline to insert horizontal lines:
    \hline
    \head{Command} & \head{Declaration} & \head{Output}\\
    \hline
  4. Continue with the table body and end the environment and the document. To typeset LaTeX commands literally, write \verb|\command|:
    \verb|\textrm| & \verb|\rmfamily| & \rmfamily Example text\\
    \verb|\textsf| & \verb|\sffamily| & \sffamily Example text\\
    \verb|\texttt| & \verb|\ttfamily| & \ttfamily Example text\\
    \hline
    \end{tabular}
    \end{document}
  5. Compile the document to see the table:

Figure 5.4 – A simple table

Figure 5.4 – A simple table

In step 2, we specified a list of characters in the mandatory argument. Each character defines how a column will be formatted. Since we used three characters, we’ve got three columns. The letter c stands for centered alignment, so the entries of all columns have been centered.

In steps 3 and 4, column entries are separated by an ampersand character (&), while \\ terminates a row. To improve readability, it’s a good idea to align the ampersands, &, in the source code.

Within the column entries, you may use plain text as well as LaTeX commands. Just like in the tabbing environment, declarations are local to the current cell.

Furthermore, the tabular environment has an optional positioning argument just like the minipage environment. The full definition looks like this:

\begin{tabular}[position]{column specifiers}
row 1 col 1 entry & row 1 col 2 entry ... & row 1 col n entry\\
...
\end{tabular}

The optional [position] argument sets vertical alignment of the entire table:

  • t aligns at the top row of the table
  • b aligns at the bottom row
  • c centers the table vertically, which is the default

This optional argument may come in handy if you would like to place two tables next to each other or beside an image or other text.

In the following sections, we will discuss ways to customize tables, such as drawing lines; aligning to the left, right, or center; and merging cells across multiple columns or rows.

Within a tabular environment, we can use three types of lines:

  • \hline draws a horizontal line spanning the entire width of the table.
  • \cline{m-n} draws a horizontal line starting at column m and ending at column n. Both numbers are required: even if this line should cover only one particular column, for example, just column 3, we must write it as \cline{3-3}.
  • \vline draws a vertical line across the entire height of the current row.

We’ll make use of the \hline command in the upcoming sections.

There are many more formatting options. Have a look at this example table, where we add l, c, r, and p as column specifiers, to demonstrate each kind of alignment:

\begin{tabular}{|l|c|r|p{1.7cm}|}
\hline
left & centered & right & a fully justified paragraph cell\\
\hline
l & c & r & p\\
\hline
\end{tabular}

This code generates the following table:

Figure 5.5 – A table with different alignments

Figure 5.5 – A table with different alignments

The options understood by the tabular environment are as follows:

  • l aligns content to the left.
  • c centers content.
  • r aligns content to the right.
  • p{width} is for a “paragraph” cell of a fixed width. If you place several p columns next to each other, their cells will be aligned at their top line. It behaves like using \parbox[t]{width} inside a cell.
  • @{code} inserts code instead of empty space before or after a column. The code can also be some text, or it could be left empty to suppress this space entirely, such as @{}. We’ll make frequent use of this later in this section.
  • *{n}{options} repeats the specified options n times. n is a positive integer, and the options may consist of one or more column specifiers, including * as well.
  • | draws a vertical line along the column.

It’s best to avoid using vertical lines in tables. Lines should provide subtle visual guidance without interfering with readability. Reading rows from left to right is easier without separation lines. Many scientific writing guidelines recommend this approach, and some journals even require it.

The array package offers many further features. After loading it with \usepackage{array}, you may use the following options to tabular:

  • m{width} is similar to \parbox{width}: the baseline is in the middle.
  • b{width} behaves like \parbox[b]{width}: the baseline is at the bottom.
  • !{code} inserts code. In contrast to @{…}, the space between columns will not be suppressed.
  • >{code} can be used before an l, c, r, p, m, or b option, and inserts code right at the beginning of each entry of that column. We’ll use this feature frequently to insert font commands.
  • <{code} can be used after an l, c, r, p, m, or b option, and inserts code directly at the end of the entry of that column.

This example shows loading the array package and demonstrates the effect of @{} and the p, m, and b alignment arguments:

\documentclass{article}
\usepackage{array}
\begin{document}
\begin{tabular}{@{}lp{1.2cm}m{1.2cm}b{1.2cm}@{}}
\hline
baseline & aligned at the top & aligned at the middle
& aligned at the bottom\\
\hline
\end{tabular}
\end{document}

The output table is as follows:

Figure 5.6 – A table with different vertical alignments

Figure 5.6 – A table with different vertical alignments

Notice the last column in Figure 5.6; the text isn’t visually aligned with the bottom of the table cell. That’s important to understand; the option b means that the baseline of the cell text shall be the bottom line. Then, LaTeX aligns all baselines at the same vertical level. So, to align text where the baseline is its bottom line with the other baselines, the text must shift upward. You can think of baselines as anchor lines; all cells align their content based on these shared anchor points.

Let’s now look at tweaking details and merging cells.

You might have noticed that horizontal lines in a table can come uncomfortably close to capital letters. To address this, the array package introduces a length called \extrarowheight. It’s 0 by default, but if you set it to a positive value, this adds extra vertical space above every row of the table.

The next example, following the very first example of this chapter, shows how to increase the row height in the highlighted line. It also shows the effect of further array formatting options, as follows:

\documentclass{article}
\usepackage{array}
\setlength{\extrarowheight}{4pt}
\begin{document}
\begin{tabular}{@{}>{\itshape}ll!{:}l<{.}@{}}
\hline
Info: & Software & \LaTeX\\
& Author & Leslie Lamport\\
& Website & www.latex-project.org\\
\hline
\end{tabular}
\end{document}

The output is as follows:

Figure 5.7 – A stretched table

Figure 5.7 – A stretched table

Here, we applied >{\itshape} to change the font of a column to italics. The >{...} construct is often used to insert an alignment declaration such as \centering. However, there’s a subtle issue: declarations such as the \centering command might change the internal meaning of \\, which is a shortcut for \tabularnewline within tables. But the array package offers a command to repair it. In such cases, just add the \arraybackslash command, as in the following example:

\begin{tabular}{>{\centering\arraybackslash}p{5cm}}

Without this, the text in paragraph cells stated by p, m, or b will stay fully justified.

You can also insert extra vertical space after a specific row using an optional argument for \\, such as \\[10pt].

You may even stretch a whole table: the \arraystretch command contains a stretching factor with a default value of 1. You can redefine it to increase it. For example, \renewcommand{\arraystretch}{1.5} will increase the height of the rows by a factor of 1.5, which means adding 50 percent space. Unlike \extrarowheight, it adds space both above and below the row. To keep the effect limited, place the command inside a group or an environment. Alternatively, you can reset it to the default value with \renewcommand{\arraystretch}{1}.

Our tables may still not look as polished as those in professionally typeset books. In particular, we could improve the lines and their distances from the text content. The booktabs package helps with that. By using this package, you can greatly enhance the appearance of your tables with new commands that replace \hline and \cline.

Here’s how:

  1. Using our previous example from Figure 5.4, load the booktabs package:
    \usepackage{booktabs}
  2. Use the new \toprule, \midrule, and \bottomrule commands instead of \hline. You can specify the thickness as an optional argument. The table code becomes the following:
    \begin{tabular}{ccc}
    \toprule[1.5pt]
    \head{Command} & \head{Declaration} & \head{Output}\\
    \midrule
    \verb|\textrm| & \verb|\rmfamily| & \rmfamily Example text\\
    \verb|\textsf| & \verb|\sffamily| & \sffamily Example text\\
    \verb|\texttt| & \verb|\ttfamily| & \ttfamily Example text\\
    \bottomrule[1.5pt]
    \end{tabular}
  3. Compile to see the difference:

Figure 5.8 – A stretched table

Figure 5.8 – A stretched table

Especially in British typesetting, the term rule is commonly used to refer to a line. The booktabs developer adopted this terminology for the package’s commands. These are their definitions:

  • \toprule[thickness] draws a horizontal line at the top of the table. If desired, a thickness value may be specified, such as 1pt or 0.5mm.
  • \midrule[thickness] creates a horizontal dividing line between table rows.
  • \bottomrule[thickness] draws a horizontal line to finish off a table.
  • \cmidrule[thickness](trim){m–n} draws a horizontal line from column m to column n. The (trim) argument is optional, similar to the thickness argument. It could be (l) or (r) to trim the line at its left or right end. Write (lr) to trim at both ends. You can even specify a trim width like in (l{10pt}).

The booktabs package intentionally avoids defining vertical lines. Neither vertical nor double lines are recommended for clean, professional tables. In fact, both are generally regarded as poor typographic style. Instead, rely on \toprule, \midrule, and \bottomrule. You can use them without optional arguments – let’s look at how to do that next.

We previously mentioned the \setlength command in the Increasing the row height section of this chapter. Rather than specifying a line thickness with an optional argument to \toprule, \midrule, \cmidrule, or \bottomrule, we can always omit it. Instead, we set it globally, once for our whole document, by using \setlength in the preamble.

So, for example, after \usepackage{booktabs}, you can write the following:

\setlength{\heavyrulewidth}{1.5pt}

Now just use \toprule and \bottomrule without an argument, and they will always be 1.5 pt thick.

The following booktabs package lengths can be adjusted:

  • \heavyrulewidth: The thickness of top and bottom lines with \toprule and \bottomrule
  • \lightrulewidth: The thickness of middle lines with \midrule
  • \cmidrulewidth: The thickness of \cmidrule
  • \cmidrulekern: Trimming in \cmidrule
  • \abovetopsep: The space above the top rule; the default is 0pt
  • \belowbottomsep: The space below the bottom rule; the default is 0pt
  • \aboverulesep: The space above \midrule, \cmidrule, and \bottomrule
  • \belowrulesep: The space below \midrule, \cmidrule, and \toprule

Feel free to experiment with these settings. The default values are well balanced, but you may change them. Adjustments made in your preamble will apply to all tables in your document.

To group related columns under a shared heading, we can merge table cells using the \multicolumn command.

In our example, both commands and declarations represent input, while the third column contains output. To reflect this structure, we’ll revise the header row to span columns as follows:

  1. Based on our previous example, insert a new header row. Use *{3}l to define three left-aligned columns. Put @{} before and after to remove inter-column space. Apply the \multicolumn command to merge cells. Adjust the column formatting argument and the middle rule. The changes are highlighted here:
    \begin{tabular}{@{}*{3}l@{}}
    \toprule[1.5pt]
    \multicolumn{2}{c}{\head{Input}} &
    \multicolumn{1}{c}{\head{Output}}\\
    \head{Command} & \head{Declaration} & \\
    \cmidrule(r){1-2}\cmidrule(l){3-3}
    \verb|\textrm| & \verb|\rmfamily| & \rmfamily Example text\\
    \verb|\textsf| & \verb|\sffamily| & \sffamily Example text\\
    \verb|\texttt| & \verb|\ttfamily| & \ttfamily Example text\\
    \bottomrule[1.5pt]
    \end{tabular}
  2. Compile and examine the output:

Figure 5.9 – A table with merged cells

Figure 5.9 – A table with merged cells

We used the \multicolumn command twice: once to merge two cells and, surprisingly, another time just for one cell – we’ll see in a second why. Let’s first look at its definition:

\multicolumn{number of columns}{formatting options}{entry text}

The number of columns to be spanned may be a positive integer or just 1. The formatting options will be applied instead of the options specified in the tabular definition for this cell.

We took advantage of this when we used \multicolumn{1}{c}{…}, overriding the l option of the column with a c option to get just this cell centered.

The other change we made concerns \cmidrule. We used it instead of \midrule, together with the trimming option, to get a gap between the input and the output column for improving visual clarity.

There are many more font commands that we would like to add to the table. However, writing \verb|…| commands in each cell would quickly become tedious. Instead, we can take advantage of the >{…} construct from the array package to apply formatting to entire columns.

Let’s update our tabular definition to set our input columns in the typewriter font. We’ll also add a new column on the left to describe the command’s type. Let’s go:

  1. Extend the preamble of our example by defining a \normal macro. It will use the \multicolumn command to generate an l cell, no matter what the column formatting is:
    \documentclass{article}
    \usepackage{array}
    \usepackage{booktabs}
    \newcommand{\head}[1]{\textnormal{\textbf{#1}}}
    \newcommand{\normal}[1]{\multicolumn{1}{l}{#1}}
    \begin{document}
  2. As the \verb command can’t be used in table headers, we will use \ttfamily to get the typewriter font. We’ll also use \textbackslash here to avoid repeating that long command phrase within the cells. Use *{2}>{…} to insert it twice. Then, add <{Example text} to the last column to save typing work:
    \begin{tabular}{@{}l*{2}{>{\ttfamily\textbackslash}l}l%
    <{Example text}@{}}
    \toprule[1.5pt]
    & \multicolumn{2}{c}{\head{Input}} &
    \multicolumn{1}{c}{\head{Output}}\\
  3. We’ll use our \normal macro to avoid the typewriter formatting in the header:
    & \normal{\head{Command}} & \normal{\head{Declaration}}
    & \normal{}\\
    \cmidrule(lr){2-3}\cmidrule(l){4-4}
  4. Now we continue listing the font command names:
    Family & textrm & rmfamily & \rmfamily\\
    & textsf & sffamily & \sffamily\\
    & texttt & ttfamily & \ttfamily\\
    \bottomrule[1.5pt]
    \end{tabular}
    \end{document}
  5. Compile, and then look at the result:

Figure 5.10 – A table with column formatting commands

Figure 5.10 – A table with column formatting commands

By writing >{\textbackslash\ttfamily}l, we defined a left-aligned column, where every entry automatically begins with a backslash and appears in typewriter font. We wrote *{2}{…} to define two columns of this style. Since the example text was inserted according to our table definition with <{…}>, we only needed to place the declarations in the last column without repeating the actual text.

We’ve seen how to span text across multiple columns. But what about spanning across rows? While LaTeX itself doesn’t offer a built-in command for this, the multirow package provides exactly what we need.

Let’s center the word “Family” vertically, spanning across three rows. Here’s how:

  1. In our previous example, additionally load the multirow package:
    \usepackage{multirow}
  2. Replace the word Family with \multirow{3}{*}{Family}:
    \multirow{3}{*}{Family} & textrm & rmfamily & \rmfamily\\
  3. Compile to see the small change:

Figure 5.11 – Vertically merged cells

Figure 5.11 – Vertically merged cells

We used the \multirow command to span three rows. Its definition is as follows:

\multirow{number of rows}{width}{entry text}

The entry will span that number of rows from the row on which \multirow is used. If the number is negative, it will span the rows above.

You can specify a width or just write * to use the natural width. If you set a width, LaTeX would wrap the text to fit.

The multirow command understands further optional arguments for fine-tuning. The documentation at https://texdoc.org/pkg/multirow describes this.

Now that we’ve mastered table layout, let’s look at how to add caption text.

When working on longer documents where our text references the tables, it’s helpful to add captions and numbers to our tables. Numbering the tables allows easy referencing, whereas captions give readers context about the content of the table. LaTeX has built-in support for both.

Let’s now finalize our font table. We’ll extend the table by listing additional font commands. We’ll use the first column to describe the category of the font commands, such as family, weight, and shape. Then, we’ll add another column to demonstrate the effect of combining font commands.

To finish, we shall center the table and provide a number and a caption. To do that, we will put a table environment around our example table, use the \centering command inside it, and insert a \caption command at the end of the table environment. We will add more font commands and add another column on the right, containing more examples. Let’s break it down into the following steps:

  1. Start with the article class, and load the array, booktabs, and multirow packages:
    \documentclass{article}
    \usepackage{array}
    \usepackage{booktabs}
    \usepackage{multirow}
  2. Define a macro for formatting the header cells and a macro for normal cells, which we want to be left-aligned:
    \newcommand{\head}[1]{\textnormal{\textbf{#1}}}
    \newcommand{\normal}[1]{\multicolumn{1}{l}{#1}}
  3. Begin the document:
    \begin{document}
  4. Now, we will create the table, center the content, and write up all the rows:
    \begin{table}
    \centering
    \begin{tabular}{@{}l*{2}{>{\textbackslash\ttfamily}l}%
    l<{Example text}l@{}}
    \toprule[1.5pt]
    & \multicolumn{2}{c}{\head{Input}}
    & \multicolumn{2}{c}{\head{Output}}\\
    & \normal{\head{Command}}
    & \normal{\head{Declaration}}
    & \normal{\head{Single use}} & \head{Combined}\\
    \cmidrule(lr){2-3}\cmidrule(l){4-5}
    \multirow{3}{*}{Family} & textrm & rmfamily
    & \rmfamily & \\
    & textsf & sffamily & \sffamily& \\
    & texttt & ttfamily & \ttfamily& \\
    \cmidrule(lr){2-3}\cmidrule(lr){4-4}
    \multirow{2}{1.1cm}{Weight} & textbf & bfseries
    & \bfseries
    & \multirow{2}{1.8cm}{\sffamily\bfseries Bold and
    sans-serif}\\
    & textmd & mdseries & \mdseries & \\
    \cmidrule(lr){2-3}\cmidrule(lr){4-4}
    \multirow{4}{*}{Shape} & textit & itshape
    & \itshape & \\
    & textsl & slshape & \slshape &
    \multirow{2}{1.8cm}{\sffamily\slshape Slanted and
    sans-serif}\\
    & textsc & scshape & \scshape & \\
    & textup & upshape & \upshape & \\
    \cmidrule(lr){2-3}\cmidrule(lr){4-4}
    Default & textnormal & normalfont & \normalfont & \\
    \bottomrule[1.5pt]
    \end{tabular}
    \caption{\LaTeX\ font selection}
    \end{table}
  5. End the document:
    \end{document}
  6. Compile, and our table is now ready:

Figure 5.12 – A table with a caption

Figure 5.12 – A table with a caption

We wrapped the tabular environment inside a table environment. It’s used in this way together with the \caption command:

\begin{table}[placement options]
table body
\caption{table title}
\end{table}

The table environment is a floating environment. Unlike regular text, it can appear somewhere else other than what is defined by its position in the source code. The optional placement argument determines where the table might appear. However, LaTeX will position a table within the text to achieve good page breaks without too much empty space at the end of a page. We will spend some time discussing floating environments in the next chapter, specifically in the context of graphic placement, and the same principles apply here. As we’ll see with figures in the next chapter, \begin{table}[htbp!] is the most flexible choice.

\caption understands an optional argument as well. If you write \caption[short text]{long text}, then the short text will appear in a list of tables and the long text in the document body. That’s useful if you need very long descriptive captions.

Tables are automatically numbered. Let’s talk about the positioning and formatting of captions in the following two sections.

In professional typesetting, it’s very common to place captions above tables rather than below. We can achieve this by writing \caption before the table body. However, LaTeX assumes the caption will always be below, resulting in a cramped appearance of the table. There’ll be too little space between the caption and the following table. So, you might wish to add some space, for instance, by entering \vspace{10pt} directly after a top caption.

Remember the booktabs package? If you begin tables with \toprule, just specify the \abovetopskip length, as in the following example:

\setlength{\abovetopsep}{10pt}

By putting this line into your preamble, a 10 pt space would be added below the caption and above the top line of the table.

By default, captions look like regular body text; there’s no visual difference. Would you like to have a slight change in font size, different formatting of the label, some margins or indentation, or any other customization? The caption package offers a powerful solution.

By using a few options, you can enhance the visual appearance of all of your captions. Try the following:

\usepackage[font=small,labelfont=bf,margin=1cm]{caption}

This configuration makes your captions slightly smaller than the regular text, displays the label in bold, and ensures it will not be as wide as normal text, adding a margin of 1 cm to each side of the caption. The package provides many customization features, both for document-wide settings and fine-tuning individual captions. Its documentation is extensive and helpful. Either visit https://texdoc.org/pkg/caption or type texdoc caption at the command line to learn more.

There are various packages for table layout and appearance. In the next section, we will get to know such packages.

While creating tables in LaTeX, we may face various formatting challenges. For example, we may need to adjust column widths, insert page breaks within tables, apply colors, rotate tables, and achieve a specific alignment. In the following sections, we’ll examine additional packages designed to address these needs.

You can find example tables and links to the documentation at https://latexguide.org/tables for each of the following sections.

l, c, and r columns adjust to the width of their content. For p columns, you set a fixed width. This way, it’s hard to predict the actual width of the table. Wouldn’t it be a good idea to specify the table width and let LaTeX decide how wide the columns may be? That’s exactly what the tabularx package does. Use it as follows:

\usepackage{tabularx}
...
\begin{tabularx}{width}{column specifiers}
...
\end{tabularx}

The new tabularx environment takes one extra argument: the desired width of the table. It introduces a new column type, X. It behaves like a p column, but X columns automatically stretch to fill the available space. One X column would take all of the available space. If you use several X columns, they will share the space equally. So, you could write, for instance, the following:

\begin{tabularx}{0.6\textwidth}{lcX}

This way, you would get a table occupying 60 percent of the text width – a left-aligned and a centered column as wide as their content, and a paragraph column as wide as possible until 60 percent is reached.

Despite its simplicity, the tabularx documentation provides further examples, explains the derived types, and offers advice, such as avoiding \multicolumn entries that cross any X column. Read the documentation at https://texdoc.org/pkg/tabularx or run texdoc tabularx at the command line.

There are two related approaches. Standard LaTeX provides a starred version of the tabular environment:

\begin{tabular*}{width}[position]{column specifiers}

The table adjusts to width by modifying the inter-column space. tabularx has been developed to satisfy this need in a more useful way.

The tabulary package provides another sophisticated tabular environment that takes the total width. It weights each column width according to the natural width of the widest cell in the column.

In general, the tabularx package is an excellent choice for adjusting the table width to the text width and is probably the most popular tabular package.

All the tabular environments that we’ve seen so far can’t extend across page boundaries. The tabbing environment is an exception, since it works differently.

When a table contains a large amount of data, we need another approach. There are several packages that offer different ways to handle it:

  • longtable provides an environment with the same name that’s like a multi-page version of tabular. It provides commands to set table captions, continued captions, and special headers and footers when a page break occurs. It’s probably the easiest way for multi-page tables, and therefore it’s the most popular. The package documentation describes all you need. In combination with the booktabs package, you will get excellent results. This is the most commonly used package.
  • ltxtable provides a combination of longtable and tabularx.
  • ltablex is another approach to combine the features of longtable and tabularx.
  • supertabular offers another multi-page extension of the internally used tabular environment, providing optional table tails and heads where page breaks occur. It’s recommended for two-column documents.
  • xtab extends supertabular and reduces some of its weaknesses.
  • stabular implements a simple way to use page breaks in tabular without much fuss.

If you need tables to be able to extend across multiple pages, you can check out the packages’ manuals at https://texdoc.org/, or use the texdoc command on your computer. Among them, the longtable package is probably the most popular choice.

We discussed coloring text in Chapter 2, Formatting Text and Creating Macros. To color tables, use the colortbl package. We can combine all this by using the table option with the xcolor package:

\usepackage[table]{xcolor}

The package allows coloring columns, rows, single entries, and lines in many ways. The package documentation can tell you more; find it at https://texdoc.org/pkg/xcolor.

If a table is too wide to fit in portrait mode, you can rotate it into landscape orientation. The rotating package offers an environment called sidewaystable, which behaves like the regular table environment but rotates the entire table and its caption by 90 degrees, placing it on its own page. The package includes further rotation-related environments and commands.

Columns containing numbers are more readable when the entries are aligned at the decimal point or an exponent if present. Several packages assist with this:

  • siunitx is a very modern and actively developed package primarily intended for typesetting values with units in a consistent way, according to scientific conventions. It provides a tabular column type for such decimal alignment of numbers.
  • dcolumn offers a column type for aligning at a comma, a period, or another specific character.
  • rccol defines a column type where numbers are right-centered: they are centered relative to other entries but right-aligned with each other. This way, corresponding digits are aligned along the column. siunitx would be the better choice, however.

In contrast to dcolumn and rccol, the siunitx package is newer and very powerful.

Text in very narrow columns might need special attention because justification can be difficult if there’s limited space. Here’s some advice:

  • Ensure correct hyphenation. If necessary, improve it as we did in Chapter 2, Formatting Text and Creating Macros. TeX doesn’t hyphenate the first word of a line, a box, or a table entry. So, a long word may cross the column boundary. To enforce hyphenation, insert an empty word: write \hspace{0pt} directly at the beginning.
  • Load the microtype package to improve justification. It has a significant effect, especially in narrow columns.
  • Full justification in p columns and the like may look bad because big gaps may appear. Consider using >{\raggedright\arraybackslash} for such columns.
  • From the ragged2e package, using the \RaggedRight command can give even better results and doesn’t require \arraybackslash.

These strategies help prevent unwanted gaps and improve the overall appearance of your tables.

In this chapter, you’ve learned how to create and format tables. We covered methods for organizing text into columns, adding captions, merging rows and columns, using packages to fit columns automatically, and creating colored, landscape, and even multi-page tables.

You can open the documentation for any mentioned package by running texdoc packagename at the command line or by visiting https ://texdoc.org/pkg/<packagename>.

LaTeX can also generate a list of tables, such as a table of contents. We’ll look at that in Chapter 8, Managing Contents, Indexes, and Bibliography.

LaTeX numbers our tables automatically. We can use these numbers to reference the tables. Chapter 7, Using Cross-References, is dedicated to referencing sections and objects, including tables.

The same principle applies to figures with images, which is the topic of the next chapter.