> ## Documentation Index
> Fetch the complete documentation index at: https://resources.latex-cloud-studio.com/llms.txt
> Use this file to discover all available pages before exploring further.

# LaTeX Table Tutorial: tabular, table, booktabs, and siunitx

> Learn how to create a table in LaTeX with `tabular`, `table`, `booktabs`, `multicolumn`, `multirow`, and decimal alignment examples.

export const RenderedOutput = ({title = "Rendered output", ctaHref, ctaLabel = "Open LaTeX Cloud Studio", children}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const trackEditorCta = () => {
    const target = new URL(ctaHref, window.location.href);
    globalThis.posthog?.capture?.("docs_app_cta_clicked", {
      source_page: window.location.pathname,
      source_section: "rendered_output",
      cta_variant: "first_compiled_example",
      target_url: target.toString(),
      target_utm_source: target.searchParams.get("utm_source"),
      target_utm_medium: target.searchParams.get("utm_medium"),
      target_utm_campaign: target.searchParams.get("utm_campaign"),
      target_utm_content: target.searchParams.get("utm_content")
    }, {
      transport: "sendBeacon",
      send_instantly: true
    });
  };
  return <details className="rendered-output" onToggle={event => setIsExpanded(event.currentTarget.open)}>
      <summary className="rendered-output__summary">
        <span className="rendered-output__title">{title}</span>
        <span className="rendered-output__hint" aria-hidden="true">View compiled result</span>
      </summary>
      {isExpanded && <div className="rendered-output__content">
          {children}
          {ctaHref && <aside className="rendered-output__cta" aria-label="Continue in the LaTeX editor">
              <span>
                <strong>Ready to use this syntax?</strong>
                Continue in the browser editor when you want to adapt the example in a real project.
              </span>
              <a href={ctaHref} onClick={trackEditorCta}>{ctaLabel}<span aria-hidden="true"> →</span></a>
            </aside>}
        </div>}
    </details>;
};

export const LatexSource = ({filename, source}) => {
  const [copyStatus, setCopyStatus] = useState("Copy");
  const copySource = async () => {
    try {
      await navigator.clipboard.writeText(source);
      setCopyStatus("Copied");
    } catch {
      setCopyStatus("Select and copy");
    }
  };
  return <figure className="latex-source">
      <figcaption className="latex-source__header">
        <span className="latex-source__filename">{filename}</span>
        <button type="button" className="latex-source__copy" onClick={copySource} aria-live="polite">
          {copyStatus}
        </button>
      </figcaption>
      <pre className="latex-source__pre" aria-label={`LaTeX source: ${filename}`} tabIndex="0">
        <code className="language-latex">{source}</code>
      </pre>
    </figure>;
};

export const LatexPreview = ({src, alt, caption, width, height}) => {
  const minZoom = 1;
  const maxZoom = 3;
  const zoomStep = 0.5;
  const measureSvgContent = async (assetSrc, pageWidth, pageHeight) => {
    const cacheKey = "__latexCloudSvgContentBoxCache";
    const contentBoxCache = globalThis[cacheKey] ?? new Map();
    globalThis[cacheKey] = contentBoxCache;
    if (contentBoxCache.has(assetSrc)) return contentBoxCache.get(assetSrc);
    const measurement = (async () => {
      const assetUrl = new URL(assetSrc, window.location.href);
      if (assetUrl.origin !== window.location.origin) {
        throw new Error("Rendered output must use a same-origin SVG asset.");
      }
      const response = await fetch(assetUrl, {
        credentials: "same-origin"
      });
      if (!response.ok) throw new Error(`Rendered output request failed with ${response.status}.`);
      const source = await response.text();
      const documentNode = new DOMParser().parseFromString(source, "image/svg+xml");
      if (documentNode.querySelector("parsererror")) throw new Error("Rendered output is not valid SVG.");
      const sourceSvg = documentNode.documentElement;
      sourceSvg.querySelectorAll("script, foreignObject").forEach(node => node.remove());
      [sourceSvg, ...sourceSvg.querySelectorAll("*")].forEach(node => {
        [...node.attributes].forEach(attribute => {
          if ((/^on/i).test(attribute.name)) node.removeAttribute(attribute.name);
          if ((attribute.name === "href" || attribute.name === "xlink:href") && !attribute.value.startsWith("#")) {
            node.removeAttribute(attribute.name);
          }
        });
      });
      const measurementHost = document.createElement("div");
      measurementHost.className = "latex-preview__measurement-host";
      const measuredSvg = document.importNode(sourceSvg, true);
      measuredSvg.setAttribute("aria-hidden", "true");
      measurementHost.appendChild(measuredSvg);
      document.body.appendChild(measurementHost);
      try {
        const measuredElements = [...measuredSvg.children].filter(node => !["defs", "desc", "metadata", "style", "title"].includes(node.tagName.toLowerCase()));
        const elementBounds = measuredElements.map(node => node.getBBox()).filter(box => [box.x, box.y, box.width, box.height].every(Number.isFinite) && box.width > 0 && box.height > 0);
        if (elementBounds.length === 0) {
          throw new Error("Rendered output has no measurable visible content.");
        }
        const sortedBounds = [...elementBounds].sort((left, right) => left.y - right.y);
        const clusterGap = pageHeight * 0.045;
        const clusters = [];
        sortedBounds.forEach(box => {
          const current = clusters[clusters.length - 1];
          if (!current || box.y - current.bottom > clusterGap) {
            clusters.push({
              boxes: [box],
              bottom: box.y + box.height
            });
            return;
          }
          current.boxes.push(box);
          current.bottom = Math.max(current.bottom, box.y + box.height);
        });
        const contentClusters = clusters.filter(cluster => {
          const clusterBox = cluster.boxes.reduce((combined, box) => {
            const right = Math.max(combined.x + combined.width, box.x + box.width);
            const bottom = Math.max(combined.y + combined.height, box.y + box.height);
            const x = Math.min(combined.x, box.x);
            const y = Math.min(combined.y, box.y);
            return {
              x,
              y,
              width: right - x,
              height: bottom - y
            };
          });
          const centerY = clusterBox.y + clusterBox.height / 2;
          const isMarginFurniture = cluster.boxes.length <= 2 && clusterBox.width < pageWidth * 0.2 && clusterBox.height < pageHeight * 0.04 && (centerY < pageHeight * 0.08 || centerY > pageHeight * 0.8);
          return !isMarginFurniture;
        });
        const visibleBounds = (contentClusters.length > 0 ? contentClusters : clusters).flatMap(cluster => cluster.boxes);
        const bounds = visibleBounds.reduce((combined, box) => {
          const right = Math.max(combined.x + combined.width, box.x + box.width);
          const bottom = Math.max(combined.y + combined.height, box.y + box.height);
          const x = Math.min(combined.x, box.x);
          const y = Math.min(combined.y, box.y);
          return {
            x,
            y,
            width: right - x,
            height: bottom - y
          };
        });
        const clampValue = (value, minimum, maximum) => Math.min(maximum, Math.max(minimum, value));
        const padding = Math.max(8, Math.min(pageWidth, pageHeight) * 0.025);
        const x = clampValue(bounds.x - padding, 0, pageWidth);
        const y = clampValue(bounds.y - padding, 0, pageHeight);
        const right = clampValue(bounds.x + bounds.width + padding, 0, pageWidth);
        const bottom = clampValue(bounds.y + bounds.height + padding, 0, pageHeight);
        return {
          x,
          y,
          width: right - x,
          height: bottom - y
        };
      } finally {
        measurementHost.remove();
      }
    })();
    contentBoxCache.set(assetSrc, measurement);
    measurement.catch(() => contentBoxCache.delete(assetSrc));
    return measurement;
  };
  const renderPreviewAsset = ({contentBox: assetContentBox, loading}) => {
    if (!assetContentBox) {
      return <img className="latex-preview__asset" src={src} alt={alt} width={width} height={height} loading={loading} draggable="false" />;
    }
    return <svg className="latex-preview__asset" viewBox={`${assetContentBox.x} ${assetContentBox.y} ${assetContentBox.width} ${assetContentBox.height}`} preserveAspectRatio="xMidYMid meet" role="img" aria-label={alt}>
        <image href={src} x="0" y="0" width={width} height={height} />
      </svg>;
  };
  const [isOpen, setIsOpen] = useState(false);
  const [frameMode, setFrameMode] = useState("content");
  const [viewMode, setViewMode] = useState("fit");
  const [zoom, setZoom] = useState(minZoom);
  const [contentBox, setContentBox] = useState(null);
  const [measurementStatus, setMeasurementStatus] = useState("loading");
  const dialogRef = useRef(null);
  const closeButtonRef = useRef(null);
  const viewportRef = useRef(null);
  const previousFocusRef = useRef(null);
  const dragRef = useRef(null);
  useEffect(() => {
    let isCurrent = true;
    setMeasurementStatus("loading");
    measureSvgContent(src, width, height).then(box => {
      if (!isCurrent) return;
      setContentBox(box);
      setMeasurementStatus("ready");
    }).catch(() => {
      if (!isCurrent) return;
      setContentBox(null);
      setFrameMode("page");
      setMeasurementStatus("error");
    });
    return () => {
      isCurrent = false;
    };
  }, [height, src, width]);
  const closeViewer = useCallback(() => {
    setIsOpen(false);
  }, []);
  const openViewer = () => {
    previousFocusRef.current = document.activeElement;
    setFrameMode(contentBox ? "content" : "page");
    setViewMode("fit");
    setZoom(minZoom);
    setIsOpen(true);
  };
  const applyZoom = useCallback(nextZoom => {
    const boundedZoom = Math.min(maxZoom, Math.max(minZoom, nextZoom));
    setViewMode("custom");
    setZoom(boundedZoom);
  }, []);
  const zoomIn = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom + zoomStep : zoom + zoomStep);
  }, [applyZoom, viewMode, zoom]);
  const zoomOut = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom : zoom - zoomStep);
  }, [applyZoom, viewMode, zoom]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    closeButtonRef.current?.focus();
    return () => {
      document.body.style.overflow = previousOverflow;
      previousFocusRef.current?.focus?.();
    };
  }, [isOpen]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const handleKeyDown = event => {
      if (event.key === "Escape") {
        event.preventDefault();
        closeViewer();
        return;
      }
      if ((event.key === "+" || event.key === "=") && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomIn();
        return;
      }
      if (event.key === "-" && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomOut();
        return;
      }
      if (event.key !== "Tab" || !dialogRef.current) return;
      const focusable = [...dialogRef.current.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')];
      if (focusable.length === 0) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [closeViewer, isOpen, zoomIn, zoomOut]);
  const startDrag = event => {
    if (event.button !== 0 || !viewportRef.current) return;
    const viewport = viewportRef.current;
    dragRef.current = {
      pointerId: event.pointerId,
      x: event.clientX,
      y: event.clientY,
      scrollLeft: viewport.scrollLeft,
      scrollTop: viewport.scrollTop
    };
    viewport.setPointerCapture(event.pointerId);
    viewport.dataset.dragging = "true";
  };
  const continueDrag = event => {
    const drag = dragRef.current;
    const viewport = viewportRef.current;
    if (!drag || !viewport || drag.pointerId !== event.pointerId) return;
    viewport.scrollLeft = drag.scrollLeft - (event.clientX - drag.x);
    viewport.scrollTop = drag.scrollTop - (event.clientY - drag.y);
  };
  const stopDrag = event => {
    const viewport = viewportRef.current;
    if (viewport?.hasPointerCapture(event.pointerId)) viewport.releasePointerCapture(event.pointerId);
    if (viewport) delete viewport.dataset.dragging;
    dragRef.current = null;
  };
  const activeContentBox = frameMode === "content" ? contentBox : null;
  const activeWidth = activeContentBox?.width ?? width;
  const activeHeight = activeContentBox?.height ?? height;
  const activeRatio = activeWidth / activeHeight;
  const inlineContentBox = measurementStatus === "ready" ? contentBox : null;
  const inlineWidth = inlineContentBox?.width ?? width;
  const inlineHeight = inlineContentBox?.height ?? height;
  const inlineGeometry = {
    aspectRatio: `${inlineWidth} / ${inlineHeight}`,
    maxWidth: `${30 * inlineWidth / inlineHeight}rem`
  };
  const imageStyle = viewMode === "fit" ? {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: "100%",
    maxWidth: `${Math.max(16, activeRatio * 78)}dvh`
  } : {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: `${zoom * 100}%`,
    maxWidth: "none"
  };
  const zoomLabel = viewMode === "fit" ? frameMode === "content" ? "Fit content" : "Full page" : `${Math.round(zoom * 100)}%`;
  return <figure className="latex-preview">
      <button type="button" className="latex-preview__trigger" onClick={openViewer} aria-haspopup="dialog" aria-label={`Open zoomable preview: ${alt}`}>
        <span className="latex-preview__page" style={inlineGeometry}>
          {measurementStatus === "loading" ? <span className="latex-preview__loading" role="status">Preparing compiled output…</span> : renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: inlineContentBox,
    loading: "lazy"
  })}
        </span>
        <span className="latex-preview__trigger-label" aria-hidden="true">
          <span className="latex-preview__trigger-icon">⌕</span>
          Open viewer
        </span>
      </button>
      <figcaption className="latex-preview__caption">
        <span>
          {caption}
          {measurementStatus === "error" && <span className="latex-preview__status" role="status"> Content fit is unavailable; the complete vector page is shown.</span>}
        </span>
        <a href={src} target="_blank" rel="noreferrer" className="latex-preview__source-link">Open SVG</a>
      </figcaption>

      {isOpen && <div className="latex-preview__backdrop" onMouseDown={event => {
    if (event.target === event.currentTarget) closeViewer();
  }}>
          <section ref={dialogRef} className="latex-preview__dialog" role="dialog" aria-modal="true" aria-label={`Rendered LaTeX viewer: ${alt}`}>
            <header className="latex-preview__toolbar">
              <div className="latex-preview__identity">
                <span className="latex-preview__eyebrow">Compiled LaTeX</span>
                <span className="latex-preview__filename">{alt}</span>
              </div>
              <div className="latex-preview__controls" aria-label="Preview controls">
                <button type="button" className={frameMode === "content" && viewMode === "fit" ? "is-active" : undefined} disabled={!contentBox} onClick={() => {
    setFrameMode("content");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Fit content
                </button>
                <button type="button" className={frameMode === "page" && viewMode === "fit" ? "is-active" : undefined} onClick={() => {
    setFrameMode("page");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Full page
                </button>
                <span className="latex-preview__zoom-group">
                  <button type="button" onClick={zoomOut} disabled={viewMode === "fit" || zoom <= minZoom} aria-label="Zoom out">−</button>
                  <output aria-live="polite" aria-label="Current zoom">{zoomLabel}</output>
                  <button type="button" onClick={zoomIn} disabled={viewMode !== "fit" && zoom >= maxZoom} aria-label="Zoom in">+</button>
                </span>
                <a href={src} target="_blank" rel="noreferrer">Open SVG</a>
                <button ref={closeButtonRef} type="button" className="latex-preview__close" onClick={closeViewer} aria-label="Close rendered LaTeX viewer">
                  Close
                </button>
              </div>
            </header>
            <div ref={viewportRef} className="latex-preview__viewport" data-view-mode={viewMode} onPointerDown={startDrag} onPointerMove={continueDrag} onPointerUp={stopDrag} onPointerCancel={stopDrag}>
              <span className="latex-preview__dialog-page" style={imageStyle}>
                {renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: activeContentBox
  })}
              </span>
            </div>
            <footer className="latex-preview__viewer-note">
              Compiler-generated vector output · Use +/− to zoom · Drag to pan · Esc to close
            </footer>
          </section>
        </div>}
    </figure>;
};

To create a table in LaTeX, start with a `tabular` environment, separate columns with `&`, and end each row with `\\`. Wrap that `tabular` block in a `table` environment when you need a caption, label, or float positioning. This guide starts with the basic LaTeX table syntax most people need first, then moves into `booktabs`, decimal alignment, and multi-column or multi-row layouts.

If you only need the fastest possible answer:

* Use `tabular` to build the rows and columns.
* Use `table` when you need a floating table with a caption and label.
* Use `booktabs` when you want journal-style horizontal rules.
* Use `siunitx` when numbers need to align at decimal points.

<Info>
  **Package required**: Basic tables work with the `tabular` environment. For professional tables, add `\usepackage{booktabs}`. For decimal alignment, use `\usepackage{siunitx}`.

  **Need the `tabular` syntax only?** Start with the focused [tabular environment guide](/learn/latex/tables/tabular).

  **Related topics**: [Mathematical matrices](/learn/latex/mathematics/matrices) | [Figure positioning](/learn/latex/figures/positioning) | [Cross-referencing tables](/learn/latex/cross-referencing)

  **Last updated**: April 2026 | **Reading time**: 25 min | **Difficulty**: Beginner to Advanced
</Info>

## What You'll Learn

* ✅ Basic table structure with `tabular` environment
* ✅ Column alignment and formatting options
* ✅ Professional tables with `booktabs` package
* ✅ Multi-column and multi-row cells
* ✅ Decimal alignment for numeric data
* ✅ Table captions and cross-references
* ✅ Advanced formatting techniques
* ✅ Troubleshooting common LaTeX table issues

## Frequently Asked Questions

<Accordion title="What is the difference between table and tabular in LaTeX?">
  The main difference between `table` and `tabular` in LaTeX is their **purpose**:

  * **tabular** is the actual table content - it creates the rows, columns, and cell data
  * **table** is a **float container** that wraps tabular for positioning, captions, and labels

  You typically nest `tabular` inside `table`:

  <LatexSource filename="example.tex" source={"\\begin{table}[htbp]\n  \\centering\n  \\caption{My table caption}\n  \\label{tab:mytable}\n  \\begin{tabular}{lcc}\n    Header 1 & Header 2 & Header 3 \\\\\n    Data & Data & Data \\\\\n  \\end{tabular}\n\\end{table}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-22/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **When to use each:**

  * Use **tabular alone** for inline tables without captions
  * Use **table + tabular** when you need positioning control, captions, or cross-references
</Accordion>

<Accordion title="How do I align numbers at decimal points in LaTeX tables?">
  To **align decimal points** in LaTeX tables, use the `siunitx` package with the S-type column:

  <LatexSource filename="example.tex" source={"\\usepackage{siunitx}\n\\begin{tabular}{l S[table-format=3.2]}\n\\hline\nItem & {Value} \\\\\n\\hline\nProduct A & 12.5 \\\\\nProduct B & 123.45 \\\\\nProduct C & 1.234 \\\\\n\\hline\n\\end{tabular}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-23/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
  </RenderedOutput>

  **How it works:**

  * `S[table-format=3.2]` means 3 digits before decimal, 2 after
  * Wrap text headers in `{braces}` to prevent siunitx parsing
  * Numbers automatically align at the decimal point

  This is essential for financial data, scientific measurements, and any numeric tables.
</Accordion>

<Accordion title="What is booktabs and why should I use it for LaTeX tables?">
  **booktabs** is a LaTeX package that provides professional-quality horizontal rules for tables:

  * `\toprule` - Thick line at table top
  * `\midrule` - Medium line between header and body
  * `\bottomrule` - Thick line at table bottom

  <LatexSource filename="example.tex" source={"\\usepackage{booktabs}\n\\begin{tabular}{lcc}\n\\toprule\nHeader 1 & Header 2 & Header 3 \\\\\n\\midrule\nData 1 & Data 2 & Data 3 \\\\\nData 4 & Data 5 & Data 6 \\\\\n\\bottomrule\n\\end{tabular}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-24/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **Why use booktabs:**

  * Better spacing around rules (no cramped rows)
  * Professional appearance matching journal standards
  * Avoids vertical lines (considered bad practice)
  * Required by many academic publishers (Nature, IEEE, etc.)
</Accordion>

<Accordion title="How do I make a cell span multiple columns in LaTeX?">
  Use `\multicolumn{n}{alignment}{text}` to span n columns:

  <LatexSource filename="example.tex" source={"\\begin{tabular}{lcc}\n\\hline\n\\multicolumn{3}{c}{Spanning Three Columns} \\\\\n\\hline\nLeft & Center & Right \\\\\n\\multicolumn{2}{l}{Spans two columns} & Right \\\\\n\\hline\n\\end{tabular}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-25/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **Parameters:**

  * `{3}` - Number of columns to span
  * `{c}` - Alignment (l, c, r, or with borders like `|c|`)
  * `{text}` - Cell content

  **Common uses:**

  * Table titles spanning all columns
  * Grouped headers for related columns
  * Footnotes or notes spanning the table width
</Accordion>

<Accordion title="How do I make a cell span multiple rows in LaTeX?">
  Use the `multirow` package with `\multirow{n}{width}{text}`:

  <LatexSource filename="example.tex" source={"\\usepackage{multirow}\n\\begin{tabular}{lcc}\n\\hline\n\\multirow{2}{*}{Category} & Value 1 & 100 \\\\\n                          & Value 2 & 200 \\\\\n\\hline\n\\multirow{3}{*}{Group A}  & Item 1  & 10 \\\\\n                          & Item 2  & 20 \\\\\n                          & Item 3  & 30 \\\\\n\\hline\n\\end{tabular}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-26/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **Parameters:**

  * `{2}` or `{3}` - Number of rows to span
  * `{*}` - Auto width (or specify like `{3cm}`)
  * `{text}` - Cell content

  Leave the corresponding cells in subsequent rows empty (just use `&`).
</Accordion>

<Accordion title="How do I add colors to LaTeX table rows and cells?">
  Use the `xcolor` package with the `table` option:

  <LatexSource filename="example.tex" source={"\\usepackage[table]{xcolor}\n\n% Color entire row\n\\rowcolor{gray!20}\nHeader 1 & Header 2 & Header 3 \\\\\n\n% Color single cell\nNormal & \\cellcolor{yellow}Highlighted & Normal \\\\\n\n% Alternating row colors (zebra striping)\n\\rowcolors{2}{white}{gray!10}\n\\begin{tabular}{lcc}\n...\n\\end{tabular}"} />

  <RenderedOutput title="Expected effect">
    <Info>
      This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
    </Info>
  </RenderedOutput>

  **Color syntax:**

  * `gray!20` = 20% gray (lighter)
  * `red!50` = 50% red
  * `blue!10` = 10% blue (very light)
  * Standard colors: red, green, blue, yellow, cyan, magenta, black, white
</Accordion>

<Accordion title="How do I make a table fit the page width in LaTeX?">
  Use the `tabularx` package with the X column type:

  <LatexSource filename="example.tex" source={"\\usepackage{tabularx}\n\\begin{tabularx}{\\textwidth}{lXr}\n\\hline\nFixed left & This column expands to fill space & Fixed right \\\\\n\\hline\n\\end{tabularx}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-28/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **Options for wide tables:**

  1. **tabularx** with `X` columns - columns expand to fill `\textwidth`
  2. **Multiple X columns** - `{|X|X|X|}` distributes space equally
  3. **resizebox** - scales entire table: `\resizebox{\textwidth}{!}{\begin{tabular}...}`
  4. **Smaller font** - `{\small \begin{tabular}...}` or `\footnotesize`
  5. **Rotating** - `\usepackage{rotating}` with `sidewaystable` for landscape
</Accordion>

<Accordion title="How do I fix table positioning problems in LaTeX?">
  Control table positioning with float placement specifiers:

  <LatexSource filename="example.tex" source={"\\begin{table}[htbp]  % Try here, top, bottom, page\n\\begin{table}[H]     % Force exact position (requires float package)"} />

  <RenderedOutput title="Expected effect">
    <Info>
      This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
    </Info>
  </RenderedOutput>

  **Placement options:**

  * `h` - Here (approximately)
  * `t` - Top of page
  * `b` - Bottom of page
  * `p` - Page of floats only
  * `H` - HERE exactly (requires `\usepackage{float}`)
  * `!` - Override LaTeX's restrictions

  **Common issues and fixes:**

  * Table floats away: Use `[H]` with float package
  * Table at wrong page: Use `[t]` or adjust surrounding content
  * Too many floats: Use `\clearpage` to flush pending floats
  * Want inline table: Use `tabular` without `table` wrapper
</Accordion>

<Accordion title="How do I create a table that spans multiple pages in LaTeX?">
  Use the `longtable` package for tables that break across pages:

  <LatexSource filename="example.tex" source={"\\usepackage{longtable}\n\\usepackage{booktabs}\n\n\\begin{longtable}{lcc}\n\\caption{Multi-page table example} \\\\\n\\toprule\nHeader 1 & Header 2 & Header 3 \\\\\n\\midrule\n\\endfirsthead\n\n\\multicolumn{3}{c}{\\textit{Continued from previous page}} \\\\\n\\toprule\nHeader 1 & Header 2 & Header 3 \\\\\n\\midrule\n\\endhead\n\n\\midrule\n\\multicolumn{3}{r}{\\textit{Continued on next page}} \\\\\n\\endfoot\n\n\\bottomrule\n\\endlastfoot\n\n% Your data rows here\nRow 1 & Data & Data \\\\\nRow 2 & Data & Data \\\\\n% ... many more rows\n\\end{longtable}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-30/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **Key commands:**

  * `\endfirsthead` - Header for first page only
  * `\endhead` - Header for continuation pages
  * `\endfoot` - Footer for pages that continue
  * `\endlastfoot` - Footer for final page

  **Note:** Unlike `table`, `longtable` is NOT a float - it appears exactly where placed in your document.
</Accordion>

<Accordion title="How do I fix row spacing in LaTeX tables?">
  LaTeX table rows can appear cramped. Here are solutions:

  **Method 1: Adjust arraystretch (global)**

  <LatexSource filename="example.tex" source={"\\renewcommand{\\arraystretch}{1.3}  % 1.3x normal spacing\n\\begin{tabular}{lcc}\n...\n\\end{tabular}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-31/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **Method 2: Add struts (per-row control)**

  <LatexSource filename="example.tex" source={"\\begin{tabular}{lcc}\nHeader 1 & Header 2 & Header 3 \\\\[6pt]  % Extra space after this row\nData 1 & Data 2 & Data 3 \\\\\n\\end{tabular}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-32/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **Method 3: Use booktabs (recommended)**

  <LatexSource filename="example.tex" source={"\\usepackage{booktabs}\n\\begin{tabular}{lcc}\n\\toprule\nHeader \\\\\n\\midrule\nData \\\\  % booktabs automatically adds proper spacing\n\\bottomrule\n\\end{tabular}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-33/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **Method 4: cellspace package for consistent padding**

  <LatexSource filename="example.tex" source={"\\usepackage{cellspace}\n\\setlength{\\cellspacetoplimit}{4pt}\n\\setlength{\\cellspacebottomlimit}{4pt}"} />

  <RenderedOutput title="Expected effect">
    <Info>
      This is setup or structural LaTeX code. It changes available commands or document behavior, but it does not produce meaningful standalone page content by itself.
    </Info>
  </RenderedOutput>

  The `booktabs` package is generally the best solution as it handles spacing automatically with professional results.
</Accordion>

## Basic Table Structure

### Simple Tabular Environment

<LatexSource filename="basic-table.tex" source={"\\documentclass{article}\n\\begin{document}\n\n% Basic table without float\n\\begin{tabular}{lcr}\nLeft & Center & Right \\\\\n1 & 2 & 3 \\\\\n4 & 5 & 6\n\\end{tabular}\n\n% With horizontal lines\n\\begin{tabular}{|l|c|r|}\n\\hline\nName & Age & Score \\\\\n\\hline\nAlice & 25 & 95 \\\\\nBob & 30 & 87 \\\\\nCarol & 28 & 92 \\\\\n\\hline\n\\end{tabular}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output" ctaHref="https://app.latex-cloud-studio.com/?utm_source=resources&utm_medium=rendered_output&utm_campaign=docs_open_app&utm_content=learn_latex_tables_creating_tables">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-01/page-1.svg" alt="Compiled PDF page 1 from basic-table.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Column Specifications

| Specifier  | Alignment | Description                       |               |
| ---------- | --------- | --------------------------------- | ------------- |
| `l`        | Left      | Left-aligned column               |               |
| `c`        | Center    | Centered column                   |               |
| `r`        | Right     | Right-aligned column              |               |
| `p{width}` | Justified | Paragraph column with fixed width |               |
| \`         | \`        | —                                 | Vertical line |
| `@{...}`   | —         | Custom column separator           |               |

<LatexSource filename="column-types.tex" source={"% Various column types\n\\begin{tabular}{lcrp{3cm}}\nLeft & Center & Right & Paragraph text that wraps \\\\\n\\end{tabular}\n\n% Custom spacing\n\\begin{tabular}{l@{\\hspace{2cm}}r}\nName & Value \\\\\n\\end{tabular}\n\n% Remove default spacing\n\\begin{tabular}{@{}lcr@{}}\nNo space & on & sides \\\\\n\\end{tabular}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-02/page-1.svg" alt="Compiled PDF page 1 from column-types.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

## Table Float Environment

### Basic Table with Caption

<LatexSource filename="table-float.tex" source={"\\documentclass{article}\n\\usepackage{caption}\n\\begin{document}\n\n\\begin{table}[htbp]\n  \\centering\n  \\caption{Student grades}\n  \\label{tab:grades}\n  \\begin{tabular}{lcc}\n    \\hline\n    Student & Midterm & Final \\\\\n    \\hline\n    Alice & 85 & 92 \\\\\n    Bob & 78 & 88 \\\\\n    Carol & 92 & 95 \\\\\n    \\hline\n  \\end{tabular}\n\\end{table}\n\nAs shown in Table \\ref{tab:grades}, all students improved.\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-03/page-1.svg" alt="Compiled PDF page 1 from table-float.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Table Positioning

<LatexSource filename="table-positioning.tex" source={"% Positioning options\n\\begin{table}[h]    % Here\n\\begin{table}[t]    % Top of page\n\\begin{table}[b]    % Bottom of page\n\\begin{table}[p]    % Page of floats\n\\begin{table}[htbp] % Try here, top, bottom, page\n\n% Force exact placement\n\\usepackage{float}\n\\begin{table}[H]    % HERE exactly"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

## Lines and Rules

### Horizontal Lines

<LatexSource filename="horizontal-lines.tex" source={"\\documentclass{article}\n\\usepackage{booktabs} % For professional tables\n\\begin{document}\n\n% Basic lines\n\\begin{tabular}{lcc}\n\\hline\nHeader 1 & Header 2 & Header 3 \\\\\n\\hline\nData 1 & Data 2 & Data 3 \\\\\n\\hline\n\\end{tabular}\n\n% Professional tables with booktabs\n\\begin{tabular}{lcc}\n\\toprule\nHeader 1 & Header 2 & Header 3 \\\\\n\\midrule\nData 1 & Data 2 & Data 3 \\\\\nData 4 & Data 5 & Data 6 \\\\\n\\bottomrule\n\\end{tabular}\n\n% Partial horizontal lines\n\\begin{tabular}{lcr}\nFull line \\\\\n\\hline\nPartial & line & below \\\\\n\\cline{2-3}\nOnly & under & these \\\\\n\\end{tabular}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-04/page-1.svg" alt="Compiled PDF page 1 from horizontal-lines.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

<Tip>
  **Best practice**: Use the `booktabs` package for professional-looking tables. It provides better spacing and line weights than standard LaTeX rules.
</Tip>

### Vertical Lines

<LatexSource filename="vertical-lines.tex" source={"% Single vertical lines\n\\begin{tabular}{l|c|r}\nLeft & Center & Right \\\\\n\\end{tabular}\n\n% Double vertical lines\n\\begin{tabular}{l||c||r}\nLeft & Center & Right \\\\\n\\end{tabular}\n\n% Mixed lines\n\\begin{tabular}{|l|c|r|}\n\\hline\nA & B & C \\\\\n\\hline\n1 & 2 & 3 \\\\\n\\hline\n\\end{tabular}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-05/page-1.svg" alt="Compiled PDF page 1 from vertical-lines.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

<Warning>
  **Note**: Vertical lines are generally discouraged in professional tables. They can make tables look cluttered and harder to read.
</Warning>

## Column Formatting

### Text Alignment and Width

<LatexSource filename="column-formatting.tex" source={"\\documentclass{article}\n\\usepackage{array} % Enhanced column types\n\\begin{document}\n\n% Fixed width columns\n\\begin{tabular}{p{3cm}p{3cm}p{3cm}}\nThis is a paragraph column & \nText wraps automatically & \nWithin the specified width \\\\\n\\end{tabular}\n\n% Array package column types\n\\begin{tabular}{>{\\bfseries}l c >{\\itshape}r}\nBold & Normal & Italic \\\\\nLeft & Center & Right \\\\\n\\end{tabular}\n\n% Centered fixed-width columns\n\\newcolumntype{C}[1]{>{\\centering\\arraybackslash}p{#1}}\n\\begin{tabular}{C{3cm}C{3cm}}\nCentered & Fixed Width \\\\\n\\end{tabular}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-06/page-1.svg" alt="Compiled PDF page 1 from column-formatting.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Multi-column Cells

<LatexSource filename="multicolumn.tex" source={"\\begin{tabular}{lcr}\n\\hline\n\\multicolumn{3}{c}{Spanning Three Columns} \\\\\n\\hline\nLeft & Center & Right \\\\\nA & B & C \\\\\n\\multicolumn{2}{l}{Span two} & Right \\\\\n\\hline\n\\end{tabular}\n\n% Complex headers\n\\begin{tabular}{lcc}\n\\hline\n\\multicolumn{1}{c}{Item} & \n\\multicolumn{2}{c}{Measurements} \\\\\n\\cline{2-3}\n& Length & Width \\\\\n\\hline\nBox A & 10 cm & 5 cm \\\\\nBox B & 15 cm & 8 cm \\\\\n\\hline\n\\end{tabular}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-07/page-1.svg" alt="Compiled PDF page 1 from multicolumn.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

### Multi-row Cells

<LatexSource filename="multirow.tex" source={"\\documentclass{article}\n\\usepackage{multirow}\n\\begin{document}\n\n\\begin{tabular}{lcc}\n\\hline\n\\multirow{2}{*}{Category} & Value 1 & Value 2 \\\\\n& 10 & 20 \\\\\n\\hline\n\\multirow{3}{*}{Group A} & Item 1 & 100 \\\\\n& Item 2 & 200 \\\\\n& Item 3 & 300 \\\\\n\\hline\n\\end{tabular}\n\n% With width specification\n\\begin{tabular}{lp{3cm}c}\n\\hline\n\\multirow{2}{3cm}{Long text that needs wrapping} & \nDescription & Value \\\\\n& More info & 42 \\\\\n\\hline\n\\end{tabular}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-08/page-1.svg" alt="Compiled PDF page 1 from multirow.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Numeric Alignment

### Decimal Alignment

<LatexSource filename="decimal-alignment.tex" source={"\\documentclass{article}\n\\usepackage{siunitx} % For numeric alignment\n\\begin{document}\n\n% Using siunitx S column\n\\begin{tabular}{l S[table-format=3.2]}\n\\hline\nItem & {Value} \\\\\n\\hline\nProduct A & 12.5 \\\\\nProduct B & 123.45 \\\\\nProduct C & 1.234 \\\\\n\\hline\n\\end{tabular}\n\n% Multiple numeric columns\n\\begin{tabular}{l *{3}{S[table-format=2.1]}}\n\\hline\nTest & {Run 1} & {Run 2} & {Run 3} \\\\\n\\hline\nA & 9.5 & 10.2 & 9.8 \\\\\nB & 12.1 & 11.9 & 12.3 \\\\\nC & 8.7 & 8.9 & 8.8 \\\\\n\\hline\n\\end{tabular}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-09/page-1.svg" alt="Compiled PDF page 1 from decimal-alignment.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

### Currency and Units

<LatexSource filename="currency-units.tex" source={"\\usepackage{siunitx}\n\n% Currency alignment\n\\begin{tabular}{l S[table-format=4.2, table-space-text-pre=\\$]}\n\\hline\nItem & {Price} \\\\\n\\hline\nLaptop & \\$1299.99 \\\\\nMouse & \\$29.95 \\\\\nKeyboard & \\$89.50 \\\\\n\\hline\nTotal & \\$1419.44 \\\\\n\\hline\n\\end{tabular}\n\n% Units in headers\n\\begin{tabular}{l S[table-format=3.1]}\n\\hline\nMaterial & {Density (\\si{g/cm^3})} \\\\\n\\hline\nWater & 1.0 \\\\\nIron & 7.9 \\\\\nGold & 19.3 \\\\\n\\hline\n\\end{tabular}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-10/page-1.svg" alt="Compiled PDF page 1 from currency-units.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

## Coloring Tables

### Row and Cell Colors

<LatexSource filename="colored-tables.tex" source={"\\documentclass{article}\n\\usepackage[table]{xcolor}\n\\begin{document}\n\n% Alternating row colors\n\\begin{tabular}{lcc}\n\\rowcolor{gray!20}\nHeader 1 & Header 2 & Header 3 \\\\\nRow 1 & Data & Data \\\\\n\\rowcolor{gray!10}\nRow 2 & Data & Data \\\\\nRow 3 & Data & Data \\\\\n\\rowcolor{gray!10}\nRow 4 & Data & Data \\\\\n\\end{tabular}\n\n% Individual cell colors\n\\begin{tabular}{lcc}\n\\hline\nNormal & \\cellcolor{yellow}Highlighted & Normal \\\\\n\\cellcolor{red!20}Light red & Normal & \\cellcolor{blue!20}Light blue \\\\\n\\hline\n\\end{tabular}\n\n% Column colors\n\\begin{tabular}{>{\\columncolor{gray!20}}l cc}\nGray column & Normal & Normal \\\\\n\\end{tabular}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-11/page-1.svg" alt="Compiled PDF page 1 from colored-tables.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

### Professional Striped Tables

<LatexSource filename="striped-tables.tex" source={"\\usepackage[table]{xcolor}\n\\usepackage{booktabs}\n\n% Define alternating colors\n\\rowcolors{2}{white}{gray!10}\n\n\\begin{tabular}{lcc}\n\\toprule\n\\rowcolor{gray!40}\nProduct & Quantity & Price \\\\\n\\midrule\nApples & 10 & \\$5.00 \\\\\nOranges & 15 & \\$7.50 \\\\\nBananas & 20 & \\$4.00 \\\\\nGrapes & 5 & \\$6.00 \\\\\n\\bottomrule\n\\end{tabular}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-12/page-1.svg" alt="Compiled PDF page 1 from striped-tables.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

## Table Width Control

### Full Width Tables

<LatexSource filename="full-width-tables.tex" source={"\\documentclass{article}\n\\usepackage{tabularx}\n\\begin{document}\n\n% Using tabularx\n\\begin{tabularx}{\\textwidth}{lXr}\n\\hline\nLeft & Expanding middle column & Right \\\\\n\\hline\nA & This column expands to fill available space & 100 \\\\\nB & Automatically adjusts width & 200 \\\\\n\\hline\n\\end{tabularx}\n\n% Multiple X columns\n\\begin{tabularx}{\\textwidth}{|X|X|X|}\n\\hline\nEqual & Width & Columns \\\\\n\\hline\nThese three columns & share the available & space equally \\\\\n\\hline\n\\end{tabularx}\n\n% Custom width distribution\n\\begin{tabularx}{\\textwidth}{l>{\\hsize=.5\\hsize}X>{\\hsize=1.5\\hsize}Xr}\nFixed & Narrow & Wide expanding column & Fixed \\\\\n\\end{tabularx}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-13/page-1.svg" alt="Compiled PDF page 1 from full-width-tables.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Resizing Tables

<LatexSource filename="resizing-tables.tex" source={"\\usepackage{graphicx}\n\n% Scale to specific width\n\\resizebox{\\textwidth}{!}{%\n\\begin{tabular}{lcccccc}\n\\hline\nMany & Columns & That & Would & Be & Too & Wide \\\\\n\\hline\nData & Data & Data & Data & Data & Data & Data \\\\\n\\hline\n\\end{tabular}\n}\n\n% Scale to fit column width\n\\resizebox{\\columnwidth}{!}{%\n\\begin{tabular}{lcr}\n% Table content\n\\end{tabular}\n}\n\n% Scale by percentage\n\\scalebox{0.8}{%\n\\begin{tabular}{lcr}\n% 80% of original size\n\\end{tabular}\n}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-14/page-1.svg" alt="Compiled PDF page 1 from resizing-tables.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

## Table Design Principles

### Professional Table Design Guidelines

Creating professional tables in LaTeX requires attention to both technical implementation and design principles. Here are the key guidelines that will elevate your table design:

<CardGroup cols={2}>
  <Card title="Clarity First" icon="eye" color="#FF6037">
    Tables should communicate data clearly. Avoid unnecessary decorations that distract from the content.
  </Card>

  <Card title="Consistent Formatting" icon="palette" color="#FF6037">
    Use consistent number formats, alignment, and styling throughout your document.
  </Card>

  <Card title="Appropriate Spacing" icon="arrows-alt-v" color="#FF6037">
    Proper spacing makes tables more readable. Use `\arraystretch` or booktabs for better spacing.
  </Card>

  <Card title="Meaningful Headers" icon="heading" color="#FF6037">
    Clear, descriptive headers help readers understand your data structure immediately.
  </Card>
</CardGroup>

### When to Use Tables vs Other Formats

Not all data belongs in a table. Consider these alternatives:

| Data Type                 | Best Format   | When to Use                                                  |
| ------------------------- | ------------- | ------------------------------------------------------------ |
| **Few data points**       | Inline text   | When you have 2-3 values that can be mentioned in a sentence |
| **Trends over time**      | Line graph    | When showing how values change over a continuous variable    |
| **Proportions**           | Pie/bar chart | When showing parts of a whole or comparing categories        |
| **Complex relationships** | Diagram       | When showing connections or flow between elements            |
| **Structured lists**      | Tables        | When comparing multiple attributes across items              |

## Advanced Table Techniques

### Creating Publication-Quality Tables

Professional journals often have specific requirements for tables. Here's how to meet common standards:

<LatexSource filename="publication-table.tex" source={"\\documentclass{article}\n\\usepackage{booktabs}\n\\usepackage{siunitx}\n\\usepackage{threeparttable}\n\\usepackage[font=small,labelfont=bf]{caption}\n\n\\begin{document}\n\n\\begin{table}[htbp]\n\\centering\n\\small % Reduce font size for journal requirements\n\\caption{Comparison of experimental results across different conditions}\n\\label{tab:results}\n\\begin{threeparttable}\n\\begin{tabular}{@{}lS[table-format=3.1]S[table-format=2.1]S[table-format=1.3]@{}}\n\\toprule\nCondition & {Temperature (\\si{\\celsius})} & {Time (h)} & {Yield} \\\\\n\\midrule\nControl\\tnote{a} & 25.0 & 2.0 & 0.850 \\\\\nOptimized\\tnote{b} & 35.5 & 1.5 & 0.923 \\\\\nModified & 30.2 & 1.8 & 0.891 \\\\\n\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\n\\footnotesize\n\\item[a] Standard laboratory conditions\n\\item[b] Conditions optimized through preliminary experiments\n\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-15/page-1.svg" alt="Compiled PDF page 1 from publication-table.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

### Dynamic Table Generation from External Data

For reproducible research, generating tables from data files is essential:

<LatexSource filename="csv-table.tex" source={"\\documentclass{article}\n\\usepackage{pgfplotstable}\n\\usepackage{booktabs}\n\\usepackage{siunitx}\n\\usepackage{xcolor}\n\\usepackage{etoolbox}\n\n% Create sample data file\n\\begin{filecontents*}{data.csv}\nSample,Temperature,Pressure,Result\nA,25.3,101.2,Pass\nB,26.1,102.5,Pass\nC,24.8,99.8,Fail\nD,25.7,101.9,Pass\n\\end{filecontents*}\n\n\\begin{document}\n\n% Basic CSV import\n\\pgfplotstabletypeset[\n  col sep=comma,\n  string type,\n  every head row/.style={\n    before row=\\toprule,\n    after row=\\midrule\n  },\n  every last row/.style={\n    after row=\\bottomrule\n  }\n]{data.csv}\n\n% Advanced formatting\n\\pgfplotstabletypeset[\n  col sep=comma,\n  string type,\n  columns={Sample,Temperature,Result}, % Select specific columns\n  column type/.add={}{}, % Clear default column types\n  columns/Sample/.style={column name=\\textbf{Sample ID}},\n  columns/Temperature/.style={\n    column name=\\textbf{Temp. (\\si{\\celsius})},\n    fixed,\n    precision=1\n  },\n  columns/Result/.style={\n    column name=\\textbf{Status},\n    postproc cell content/.code={\n      \\ifstrequal{##1}{Pass}\n        {\\pgfkeysalso{@cell content=\\textcolor{green!60!black}{##1}}}\n        {\\pgfkeysalso{@cell content=\\textcolor{red!60!black}{##1}}}\n    }\n  }\n]{data.csv}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-16/page-1.svg" alt="Compiled PDF page 1 from csv-table.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

## Accessibility in Tables

### Making Tables Screen-Reader Friendly

While LaTeX primarily produces PDF output, considering accessibility improves document usability:

<LatexSource filename="accessible-table.tex" source={"\\documentclass{article}\n\\usepackage{booktabs}\n\\usepackage{array}\n\n% Define column type for headers\n\\newcolumntype{H}{>{\\bfseries}l}\n\n\\begin{document}\n\n% Use semantic markup\n\\begin{table}[htbp]\n\\caption{Student enrollment by department and year}\n\\label{tab:enrollment}\n\\centering\n\\begin{tabular}{H*{4}{r}}\n\\toprule\nDepartment & \\textbf{2021} & \\textbf{2022} & \\textbf{2023} \\\\\n\\midrule\nComputer Science & 245 & 289 & 312 \\\\\nMathematics & 156 & 162 & 171 \\\\\nPhysics & 98 & 103 & 99 \\\\\nChemistry & 134 & 141 & 139 \\\\\n\\midrule\n\\textbf{Total} & \\textbf{633} & \\textbf{695} & \\textbf{721} \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n% Alternative text description\n\\begin{quote}\n\\textit{Table description: This table shows student enrollment numbers across four science departments from 2021 to 2023, with totals for each year. Overall enrollment increased from 633 to 721 students.}\n\\end{quote}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-17/page-1.svg" alt="Compiled PDF page 1 from accessible-table.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Troubleshooting Complex Tables

### Common Table Problems and Solutions

<Accordion title="Table extends beyond page margins">
  **Problem**: Your table is too wide for the page.

  **Solutions**:

  1. Use `\small` or `\footnotesize` to reduce font size
  2. Use `tabularx` to automatically adjust column widths
  3. Rotate the table with `rotating` package
  4. Use `\resizebox` (last resort - can make text too small)

  <LatexSource filename="example.tex" source={"% Option 1: Reduce font size\n{\\small\n\\begin{tabular}{llllll}\n% Table content\n\\end{tabular}\n}\n\n% Option 2: Use tabularx\n\\begin{tabularx}{\\textwidth}{l*{5}{X}}\n% Content automatically fits page width\n\\end{tabularx}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-36/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>
</Accordion>

<Accordion title="Decimal points don't align">
  **Problem**: Numbers in columns don't align at decimal points.

  **Solution**: Use the `siunitx` package with S-type columns:

  <LatexSource filename="example.tex" source={"\\usepackage{siunitx}\n\\begin{tabular}{l S[table-format=3.2]}\nItem & {Value} \\\\\n\\hline\nProduct A & 12.5 \\\\\nProduct B & 123.45 \\\\\nProduct C & 1.234 \\\\\n\\end{tabular}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-37/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
  </RenderedOutput>
</Accordion>

<Accordion title="Table numbering is wrong">
  **Problem**: Tables are numbered incorrectly or out of sequence.

  **Solutions**:

  1. Check for manual `\setcounter` commands
  2. Ensure proper placement of `\caption`
  3. Use `\numberwithin{table}{section}` for section-based numbering

  <LatexSource filename="example.tex" source={"% Reset numbering by section\n\\usepackage{amsmath}\n\\numberwithin{table}{section}\n\n% Manual adjustment if needed\n\\setcounter{table}{0}"} />

  <RenderedOutput title="Expected effect">
    <Info>
      This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
    </Info>
  </RenderedOutput>
</Accordion>

## Performance Optimization for Large Tables

### Handling Tables with Thousands of Rows

<LatexSource filename="large-dataset.tex" source={"\\documentclass{article}\n\\usepackage{longtable}\n\\usepackage{array}\n\\usepackage{booktabs}\n\n% Optimize compilation for large tables\n\\usepackage{etoolbox}\n\\AtBeginEnvironment{longtable}{\\small}\n\n\\begin{document}\n\n% For very large datasets, consider:\n% 1. External processing\n% 2. Pagination\n% 3. Summary tables\n\n\\begin{longtable}{@{}lrrr@{}}\n\\caption{Large dataset with automatic page breaks} \\\\\n\\toprule\nID & Value A & Value B & Result \\\\\n\\midrule\n\\endfirsthead\n\n\\multicolumn{4}{c}{\\tablename\\ \\thetable\\ -- \\textit{Continued}} \\\\\n\\toprule\nID & Value A & Value B & Result \\\\\n\\midrule\n\\endhead\n\n\\midrule\n\\multicolumn{4}{r}{\\textit{Continued on next page}} \\\\\n\\endfoot\n\n\\bottomrule\n\\endlastfoot\n\n% Representative rows. Generate very large datasets outside TeX and input them.\n1 & 2 & 3 & 5 \\\\\n2 & 4 & 6 & 10 \\\\\n3 & 6 & 9 & 15 \\\\\n4 & 8 & 12 & 20 \\\\\n5 & 10 & 15 & 25 \\\\\n6 & 12 & 18 & 30 \\\\\n7 & 14 & 21 & 35 \\\\\n8 & 16 & 24 & 40 \\\\\n9 & 18 & 27 & 45 \\\\\n10 & 20 & 30 & 50 \\\\\n\n\\end{longtable}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-18/page-1.svg" alt="Compiled PDF page 1 from large-dataset.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Best Practices

<Tip>
  **Table design guidelines:**

  1. **Simplicity**: Less is more - avoid excessive lines and decoration
  2. **Alignment**: Right-align numbers, left-align text
  3. **Spacing**: Use adequate white space for readability
  4. **Captions**: Place captions above tables (convention)
  5. **Consistency**: Use the same style throughout your document
  6. **Booktabs**: Use `\toprule`, `\midrule`, `\bottomrule` for professional appearance
  7. **Width**: Avoid tables wider than text width
</Tip>

## Common Issues and Solutions

<Warning>
  **Troubleshooting tables:**

  1. **Table too wide**: Use `tabularx`, `\small`, or rotate the table
  2. **Text not wrapping**: Use `p{width}` columns instead of `l`, `c`, or `r`
  3. **Vertical alignment**: Use `[t]`, `[c]`, or `[b]` with `p` columns
  4. **Missing package errors**: Load required packages (`array`, `booktabs`, etc.)
  5. **Spacing issues**: Adjust `\arraystretch` or use `\renewcommand{\arraystretch}{1.2}`
</Warning>

## Comparison with Other Table Tools

### LaTeX Tables vs Word/Excel Tables

Understanding when to use LaTeX tables versus other tools:

| Feature             | LaTeX         | Word    | Excel                 |
| ------------------- | ------------- | ------- | --------------------- |
| **Precision**       | Exact control | Limited | Good for calculations |
| **Consistency**     | Excellent     | Manual  | Good within sheet     |
| **Math support**    | Native        | Limited | Basic                 |
| **Automation**      | Scriptable    | Limited | VBA/Macros            |
| **Version control** | Text-based    | Binary  | Binary                |
| **Learning curve**  | Steep         | Gentle  | Moderate              |

### Converting Tables Between Formats

<LatexSource filename="excel-to-latex.tex" source={"\\documentclass{article}\n\\usepackage{datatool}\n\n\\begin{filecontents*}{data.csv}\nName,Value,Status\nAlpha,12,Ready\nBeta,18,Review\nGamma,24,Ready\n\\end{filecontents*}\n\n\\begin{document}\n\\DTLloaddb{mydata}{data.csv}\n\n\\section*{Imported rows}\n\\DTLforeach{mydata}{%\n  \\name=Name,\\value=Value,\\status=Status}{%\n  \\textbf{\\name}: value \\value, status \\status\\par\n}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-19/page-1.svg" alt="Compiled PDF page 1 from excel-to-latex.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Real-World Table Examples

### Financial Reports

<LatexSource filename="financial-table.tex" source={"\\documentclass{article}\n\\usepackage{booktabs}\n\\usepackage{siunitx}\n\\usepackage{xcolor}\n\n\\begin{document}\n\n\\begin{table}[htbp]\n\\centering\n\\caption{Quarterly Financial Summary (in millions)}\n\\begin{tabular}{l*{4}{S[table-format=4.1]}S[table-format=+3.1]}\n\\toprule\n{Revenue Stream} & {Q1} & {Q2} & {Q3} & {Q4} & {Change (\\%)} \\\\\n\\midrule\nProduct Sales & 125.4 & 132.7 & 141.2 & 156.8 & +25.0 \\\\\nServices & 45.2 & 47.8 & 49.1 & 52.3 & +15.7 \\\\\nLicensing & 12.3 & 11.9 & 13.2 & 14.1 & +14.6 \\\\\n\\midrule\n\\textbf{Total Revenue} & 182.9 & 192.4 & 203.5 & 223.2 & +22.0 \\\\\n\\midrule\nOperating Expenses & 89.2 & 91.5 & 94.8 & 98.2 & +10.1 \\\\\n\\midrule\n\\textbf{Net Income} & \\textbf{93.7} & \\textbf{100.9} & \\textbf{108.7} & \\textbf{125.0} & \n  \\textcolor{green!60!black}{\\textbf{+33.4}} \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-20/page-1.svg" alt="Compiled PDF page 1 from financial-table.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

### Scientific Data Tables

<LatexSource filename="scientific-data.tex" source={"\\documentclass{article}\n\\usepackage{booktabs}\n\\usepackage{siunitx}\n\\usepackage{multirow}\n\n\\begin{document}\n\n\\begin{table}[htbp]\n\\centering\n\\caption{Experimental measurements with uncertainties}\n\\begin{tabular}{\n  l\n  S[table-format=2.3(1)]\n  S[table-format=3.2(2)]\n  S[table-format=1.4(1)]\n}\n\\toprule\n{Sample} & {Mass (\\si{\\gram})} & {Volume (\\si{\\milli\\liter})} & {Density (\\si{\\gram\\per\\cubic\\centi\\meter})} \\\\\n\\midrule\nWater (control) & 10.000(5) & 10.02(3) & 0.9980(8) \\\\\nSolution A & 12.345(8) & 11.23(5) & 1.0990(12) \\\\\nSolution B & 15.678(10) & 13.45(8) & 1.1658(15) \\\\\n\\multirow{2}{*}{Solution C} & 18.234(12) & 15.12(10) & 1.2061(18) \\\\\n& \\multicolumn{3}{c}{\\textit{Measurement repeated due to anomaly}} \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-21/page-1.svg" alt="Compiled PDF page 1 from scientific-data.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

## Quick Reference

### Essential Commands

| Command                         | Purpose                 |
| ------------------------------- | ----------------------- |
| `\hline`                        | Horizontal line         |
| `\cline{i-j}`                   | Partial horizontal line |
| `\multicolumn{n}{format}{text}` | Span n columns          |
| `\multirow{n}{width}{text}`     | Span n rows             |
| `&`                             | Column separator        |
| `\\`                            | Row separator           |
| `\caption{}`                    | Table caption           |
| `\label{}`                      | Reference label         |

### Column Types Summary

<LatexSource filename="example.tex" source={"l              % left-aligned\nc              % centered\nr              % right-aligned\np{3cm}         % paragraph, fixed width\n|              % vertical line\n@{text}        % custom separator\n>{decl}col     % apply declaration to column\n<{decl}        % apply declaration after column"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-tables-creating-tables-39/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
</RenderedOutput>

## Practice in LaTeX Cloud Studio

<CardGroup cols={2}>
  <Card title="Build the table in the editor" icon="cloud" href="https://app.latex-cloud-studio.com/?utm_source=resources&utm_medium=card&utm_campaign=docs_open_app&utm_content=creating_tables_open_app">
    Paste a `tabular` example into the editor, change alignment and spacing, and check the PDF output immediately.
  </Card>

  <Card title="Advanced tables next" icon="table-columns" href="/learn/latex/tables/advanced-tables?utm_source=resources&utm_medium=related_guide&utm_campaign=docs_open_app&utm_content=creating_tables_advanced_tables">
    Use this when you need longtable, multirow, decimal alignment, or more complex layouts.
  </Card>
</CardGroup>

***

## Related Topics

<CardGroup cols={2}>
  <Card title="Mathematical Matrices" icon="table-cells" href="/learn/latex/mathematics/matrices">
    Create matrices with pmatrix, bmatrix, vmatrix environments
  </Card>

  <Card title="Figure Positioning" icon="image" href="/learn/latex/figures/positioning">
    Control float placement for figures and tables
  </Card>

  <Card title="Cross-Referencing" icon="link" href="/learn/latex/cross-referencing">
    Reference tables, figures, and equations in text
  </Card>

  <Card title="Advanced Tables" icon="table-columns" href="/learn/latex/tables/advanced-tables">
    Long tables, complex layouts, and professional formatting
  </Card>
</CardGroup>

## Further Reading & References

For authoritative documentation on LaTeX table creation and formatting:

* **LaTeX Tables Guide** - The standard reference for tabular environment options and column specifications
* **booktabs Package Documentation** - Professional table rules and spacing guidelines (CTAN)
* **siunitx Package Manual** - Complete guide to number and unit formatting including decimal alignment
* **The LaTeX Companion (3rd Edition)** - Comprehensive reference for table typesetting best practices
* **Publication Style Guides** - IEEE, APA, and Nature journals specify booktabs-style tables as standard

<Info>
  **Next steps**:

  * Learn about [Long tables spanning pages](/learn/latex/tables/advanced-tables) with longtable
  * Explore [Mathematical matrices](/learn/latex/mathematics/matrices) for similar structured layouts
  * Master [Figure and table positioning](/learn/latex/figures/positioning)
</Info>

<Tip>
  **LaTeX Cloud Studio** tip: Use our real-time preview feature to instantly see how your tables render. Experiment with booktabs styling and column alignment without waiting for compilation!
</Tip>
