> ## 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.

# Cross-referencing in LaTeX

> Master LaTeX cross-referencing system. Learn to reference figures, tables, equations, sections with labels, and use advanced packages like cleveref.

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>;
};

Learn to create professional cross-references in LaTeX documents. This guide covers the complete referencing system from basic labels to advanced automated references.

<Info>
  **Why cross-references matter**: They maintain consistency automatically, update numbering when you reorganize content, and provide clickable navigation in PDF documents.
</Info>

## Basic Cross-referencing System

### Labels and References

<LatexSource filename="basic-references.tex" source={"\\documentclass{article}\n\\begin{document}\n\n\\section{Introduction}\n\\label{sec:intro}\nThis is the introduction section.\n\n\\section{Methods}\n\\label{sec:methods}\nAs mentioned in Section~\\ref{sec:intro}, we will now discuss methods.\n\n\\subsection{Data Collection}\n\\label{subsec:data}\nData collection procedures are described here.\n\n\\section{Results}\nAccording to the methods in Section~\\ref{sec:methods} and specifically\nthe data collection in Section~\\ref{subsec:data}, our results show...\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_cross_referencing">
  <LatexPreview src="/images/rendered/learn-latex-cross-referencing-01/page-1.svg" alt="Compiled PDF page 1 from basic-references.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### The Label-Reference Workflow

1. **Create labels** with `\label{prefix:name}`
2. **Reference labels** with `\ref{prefix:name}`
3. **Compile twice** to resolve all references

<LatexSource filename="label-reference-workflow.tex" source={"% Step 1: Add labels to elements you want to reference\n\\section{Literature Review}\n\\label{sec:literature}\n\n\\begin{figure}[htbp]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{diagram.png}\n  \\caption{System architecture}\n  \\label{fig:architecture}\n\\end{figure}\n\n\\begin{equation}\nE = mc^2\n\\label{eq:einstein}\n\\end{equation}\n\n% Step 2: Reference them in text\nAs shown in Figure~\\ref{fig:architecture}, the system...\nEinstein's equation (Equation~\\ref{eq:einstein}) demonstrates...\nThe literature review in Section~\\ref{sec:literature} covers..."} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

## Recommended Label Prefixes

### Standard Naming Convention

<LatexSource filename="label-conventions.tex" source={"% Sections and chapters\n\\chapter{Introduction}\n\\label{chap:intro}\n\n\\section{Background}\n\\label{sec:background}\n\n\\subsection{Previous Work}\n\\label{subsec:previous}\n\n% Figures and tables\n\\begin{figure}\n  \\caption{Results overview}\n  \\label{fig:results}\n\\end{figure}\n\n\\begin{table}\n  \\caption{Performance comparison}\n  \\label{tab:performance}\n\\end{table}\n\n% Equations\n\\begin{equation}\n  y = mx + b\n  \\label{eq:linear}\n\\end{equation}\n\n% Algorithms and listings\n\\begin{algorithm}\n  \\caption{Sorting algorithm}\n  \\label{alg:sort}\n\\end{algorithm}\n\n% Appendices\n\\appendix\n\\section{Additional Data}\n\\label{app:data}\n\n% Examples and theorems\n\\begin{theorem}\n  \\label{thm:main}\n  Statement of theorem...\n\\end{theorem}\n\n\\begin{example}\n  \\label{ex:basic}\n  Example content...\n\\end{example}"} />

<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>

### Label Naming Best Practices

| Element Type | Prefix    | Example               | Reference                   |
| ------------ | --------- | --------------------- | --------------------------- |
| Chapter      | `chap:`   | `\label{chap:intro}`  | `Chapter~\ref{chap:intro}`  |
| Section      | `sec:`    | `\label{sec:methods}` | `Section~\ref{sec:methods}` |
| Subsection   | `subsec:` | `\label{subsec:data}` | `Section~\ref{subsec:data}` |
| Figure       | `fig:`    | `\label{fig:results}` | `Figure~\ref{fig:results}`  |
| Table        | `tab:`    | `\label{tab:stats}`   | `Table~\ref{tab:stats}`     |
| Equation     | `eq:`     | `\label{eq:main}`     | `Equation~\ref{eq:main}`    |
| Algorithm    | `alg:`    | `\label{alg:sort}`    | `Algorithm~\ref{alg:sort}`  |
| Theorem      | `thm:`    | `\label{thm:main}`    | `Theorem~\ref{thm:main}`    |
| Lemma        | `lem:`    | `\label{lem:helper}`  | `Lemma~\ref{lem:helper}`    |
| Appendix     | `app:`    | `\label{app:code}`    | `Appendix~\ref{app:code}`   |

<Tip>
  **Label naming tips:**

  * Use descriptive names: `fig:sales-growth` not `fig:1`
  * Keep it concise but meaningful
  * Use hyphens for multi-word labels
  * Be consistent throughout your document
</Tip>

## Advanced Reference Commands

### Page References

<LatexSource filename="page-references.tex" source={"% Basic page reference\nSee the discussion on page~\\pageref{sec:methods}.\n\n% Combined references\nFigure~\\ref{fig:results} on page~\\pageref{fig:results} shows...\n\n% Reference with both number and page\nEquation~\\ref{eq:main} (page~\\pageref{eq:main}) demonstrates...\n\n% Checking if reference is on current page\n\\ifthenelse{\\equal{\\pageref{fig:test}}{\\thepage}}{%\n  Figure~\\ref{fig:test} above shows...\n}{%\n  Figure~\\ref{fig:test} on page~\\pageref{fig:test} shows...\n}"} />

<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>

### Equation References

<LatexSource filename="equation-references.tex" source={"\\usepackage{amsmath}\n\n% Numbered equation with reference\n\\begin{equation}\n  \\label{eq:quadratic}\n  x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}\n\\end{equation}\n\n% Reference equation in text\nThe quadratic formula (Equation~\\ref{eq:quadratic}) provides...\n\n% Using \\eqref for automatic parentheses\nThe solution is given by~\\eqref{eq:quadratic}.\n\n% Multiple equations with sub-references\n\\begin{subequations}\n\\label{eq:system}\n\\begin{align}\n  x + y &= 5 \\label{eq:system-a} \\\\\n  2x - y &= 1 \\label{eq:system-b}\n\\end{align}\n\\end{subequations}\n\n% Referencing the system and individual equations\nThe system~\\eqref{eq:system} consists of equations~\\eqref{eq:system-a}\nand~\\eqref{eq:system-b}."} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-cross-referencing-05/page-1.svg" alt="Compiled PDF page 1 from equation-references.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>

### Subfigure References

<LatexSource filename="subfigure-references.tex" source={"\\usepackage{subcaption}\n\n\\begin{figure}[htbp]\n  \\centering\n  \\begin{subfigure}[b]{0.45\\textwidth}\n    \\includegraphics[width=\\textwidth]{image1.png}\n    \\caption{First result}\n    \\label{fig:results-a}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{0.45\\textwidth}\n    \\includegraphics[width=\\textwidth]{image2.png}\n    \\caption{Second result}\n    \\label{fig:results-b}\n  \\end{subfigure}\n  \\caption{Experimental results}\n  \\label{fig:results}\n\\end{figure}\n\n% Referencing main figure and subfigures\nFigure~\\ref{fig:results} shows our experimental results.\nSpecifically, Figure~\\ref{fig:results-a} demonstrates the first outcome,\nwhile Figure~\\ref{fig:results-b} shows the second."} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

## The cleveref Package

### Smart Automatic References

<LatexSource filename="cleveref-setup.tex" source={"\\usepackage{cleveref}\n\n% cleveref automatically determines reference type\n\\cref{sec:intro}        % → section 1\n\\cref{fig:results}      % → figure 2\n\\cref{tab:data}         % → table 3\n\\cref{eq:main}          % → equation (4)\n\n% Capitalized versions\n\\Cref{sec:intro}        % → Section 1\n\\Cref{fig:results}      % → Figure 2\n\n% Multiple references\n\\cref{fig:a,fig:b,fig:c}     % → figures 1, 2 and 3\n\\cref{eq:1,eq:2,eq:3}        % → equations (1) to (3)\n\\cref{sec:intro,sec:methods} % → sections 1 and 2\n\n% Range references\n\\crefrange{fig:first}{fig:last}  % → figures 1 to 5\n\\Crefrange{eq:start}{eq:end}     % → Equations (1) to (3)"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt is part of a multi-pass cross-reference or bibliography workflow. A trustworthy final page requires the surrounding project and its auxiliary files, so this standalone code box documents the workflow without claiming a complete rendered result.
  </Info>
</RenderedOutput>

### Customizing cleveref

<LatexSource filename="cleveref-customization.tex" source={"\\usepackage{cleveref}\n\n% Customize reference formats\n\\crefname{figure}{fig.}{figs.}           % figure → fig.\n\\Crefname{figure}{Fig.}{Figs.}          % Figure → Fig.\n\n\\crefname{table}{tab.}{tabs.}           % table → tab.\n\\Crefname{table}{Tab.}{Tabs.}           % Table → Tab.\n\n\\crefname{equation}{eq.}{eqs.}          % equation → eq.\n\\Crefname{equation}{Eq.}{Eqs.}          % Equation → Eq.\n\n\\crefname{section}{sect.}{sects.}       % section → sect.\n\\Crefname{section}{Sect.}{Sects.}       % Section → Sect.\n\n% Custom theorem-like environments\n\\newtheorem{theorem}{Theorem}\n\\crefname{theorem}{theorem}{theorems}\n\\Crefname{theorem}{Theorem}{Theorems}\n\n% Usage examples\n\\cref{fig:test}     % → fig. 1\n\\Cref{fig:test}     % → Fig. 1\n\\cref{thm:main}     % → theorem 1\n\\Cref{thm:main}     % → Theorem 1"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt is part of a multi-pass cross-reference or bibliography workflow. A trustworthy final page requires the surrounding project and its auxiliary files, so this standalone code box documents the workflow without claiming a complete rendered result.
  </Info>
</RenderedOutput>

### Advanced cleveref Features

<LatexSource filename="cleveref-advanced.tex" source={"% Conjunctions and lists\n\\cref{fig:a,fig:b}              % → figures 1 and 2\n\\cref{fig:a,fig:b,fig:c}        % → figures 1, 2 and 3\n\\cref{fig:a,fig:b,fig:c,fig:d}  % → figures 1 to 4\n\n% Custom conjunctions\n\\crefname{figure}{figure}{figures}\n\\newcommand{\\crefrangeconjunction}{--}  % Change \"to\" to \"--\"\n\\crefrange{fig:first}{fig:last}         % → figures 1--5\n\n% Sorting and compression\n\\cref{fig:c,fig:a,fig:b}        % → figures 1, 2 and 3 (auto-sorted)\n\\cref{eq:1,eq:2,eq:3,eq:4,eq:5} % → equations (1) to (5) (compressed)\n\n% Cross-reference without number\n\\namecref{fig:test}             % → figure (without number)\n\\nameCref{fig:test}             % → Figure (without number)\n\n% Reference format for specific instances\n\\labelcref{fig:test}            % → 1 (just the number)\n\\labelcpageref{fig:test}        % → 5 (just the page number)"} />

<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>

## Hyperref Integration

### Clickable References

<LatexSource filename="hyperref-setup.tex" source={"\\usepackage{hyperref}\n\\usepackage{cleveref} % Load AFTER hyperref\n\n% Configure hyperref\n\\hypersetup{\n  colorlinks=true,\n  linkcolor=blue,        % Internal links\n  citecolor=green,       % Citations\n  filecolor=magenta,     % File links\n  urlcolor=cyan,         % URL links\n  bookmarks=true,        % PDF bookmarks\n  pdfborder={0 0 0}     % Remove boxes around links\n}\n\n% All references are now clickable\n\\section{Introduction}\n\\label{sec:intro}\n\n\\section{Methods}\nAs discussed in \\cref{sec:intro}...  % Clickable blue link\n\n% Customize link appearance\n\\hypersetup{\n  linkcolor=black,       % Black links\n  colorlinks=false,      % Boxes instead of colors\n  pdfborder={0 0 1}     % Thin border\n}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-cross-referencing-10/page-1.svg" alt="Compiled PDF page 1 from hyperref-setup.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>

### PDF Bookmarks and Metadata

<LatexSource filename="pdf-bookmarks.tex" source={"\\usepackage{hyperref}\n\n\\hypersetup{\n  pdftitle={Document Title},\n  pdfauthor={Author Name},\n  pdfsubject={Subject},\n  pdfkeywords={keyword1, keyword2, keyword3},\n  bookmarks=true,\n  bookmarksopen=true,\n  bookmarksdepth=3,      % Depth of bookmark tree\n  pdfstartview=FitH      % Initial view\n}\n\n% Bookmarks are automatically generated from sections\n\\section{Introduction}        % Appears in PDF bookmarks\n\\subsection{Background}       % Nested bookmark\n\\subsubsection{Related Work}  % Deeper nesting\n\n% Custom bookmark entries\n\\pdfbookmark[0]{Custom Entry}{custom}  % Level 0 bookmark\n\\pdfbookmark[1]{Sub Entry}{sub}        % Level 1 bookmark"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-cross-referencing-11/page-1.svg" alt="Compiled PDF page 1 from pdf-bookmarks.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>

## Special Reference Types

### Theorem Environments

<LatexSource filename="theorem-references.tex" source={"\\usepackage{amsthm}\n\\usepackage{cleveref}\n\n% Define theorem environments\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{proposition}[theorem]{Proposition}\n\n\\theoremstyle{definition}\n\\newtheorem{definition}[theorem]{Definition}\n\\newtheorem{example}[theorem]{Example}\n\n\\theoremstyle{remark}\n\\newtheorem{remark}[theorem]{Remark}\n\n% Configure cleveref names\n\\crefname{theorem}{theorem}{theorems}\n\\Crefname{theorem}{Theorem}{Theorems}\n\\crefname{lemma}{lemma}{lemmas}\n\\Crefname{lemma}{Lemma}{Lemmas}\n\\crefname{definition}{definition}{definitions}\n\\Crefname{definition}{Definition}{Definitions}\n\n% Usage\n\\begin{theorem}\n\\label{thm:main}\nThis is the main theorem.\n\\end{theorem}\n\n\\begin{proof}\nThe proof follows from \\cref{thm:main}...\n\\end{proof}\n\n\\begin{lemma}\n\\label{lem:helper}\nThis lemma supports the main theorem.\n\\end{lemma}\n\n% References in text\n\\Cref{thm:main} establishes... % → Theorem 1 establishes...\n\\cref{lem:helper} provides...  % → lemma 2 provides..."} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-cross-referencing-12/page-1.svg" alt="Compiled PDF page 1 from theorem-references.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>

### Algorithm References

<LatexSource filename="algorithm-references.tex" source={"\\usepackage{algorithm}\n\\usepackage{algpseudocode}\n\\usepackage{cleveref}\n\n% Configure algorithm references\n\\crefname{algorithm}{algorithm}{algorithms}\n\\Crefname{algorithm}{Algorithm}{Algorithms}\n\n\\begin{algorithm}\n\\caption{Quicksort algorithm}\n\\label{alg:quicksort}\n\\begin{algorithmic}[1]\n\\Procedure{QuickSort}{$A, p, r$}\n\\If{$p < r$}\n    \\State $q \\gets \\Call{Partition}{A, p, r}$\n    \\State \\Call{QuickSort}{$A, p, q-1$}\n    \\State \\Call{QuickSort}{$A, q+1, r$}\n\\EndIf\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}\n\n% Reference in text\n\\Cref{alg:quicksort} shows the implementation...\nThe complexity of \\cref{alg:quicksort} is..."} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-cross-referencing-13/page-1.svg" alt="Compiled PDF page 1 from algorithm-references.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>

## Cross-document References

### External References with xr Package

<LatexSource filename="external-references.tex" source={"% In main document\n\\usepackage{xr}\n\\externaldocument{chapter1}  % References chapter1.tex\n\\externaldocument{chapter2}  % References chapter2.tex\n\n% Can now reference labels from external documents\nAs shown in \\cref{fig:external-result} (from Chapter 1)...\n\\Cref{tab:comparison} in Chapter 2 demonstrates...\n\n% Avoiding label conflicts\n\\externaldocument[ch1-]{chapter1}  % Prefix all labels with \"ch1-\"\n\\externaldocument[ch2-]{chapter2}  % Prefix all labels with \"ch2-\"\n\n% References now need prefixes\n\\cref{ch1-fig:result}\n\\cref{ch2-tab:data}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

### Managing Large Documents

<LatexSource filename="large-document-refs.tex" source={"% Main document structure\n% main.tex\n\\documentclass{book}\n\\usepackage{hyperref}\n\\usepackage{cleveref}\n\n% Include chapters\n\\include{chapters/introduction}    % \\input doesn't work with xr\n\\include{chapters/literature}\n\\include{chapters/methodology}\n\\include{chapters/results}\n\\include{chapters/conclusion}\n\n% Each chapter file can reference others\n% chapters/results.tex\n\\chapter{Results}\n\\label{chap:results}\n\nAs discussed in \\cref{chap:introduction}, our methodology\n(\\cref{chap:methodology}) leads to the following results...\n\n\\section{Experimental Setup}\n\\label{sec:setup}\nThe setup described here builds on \\cref{sec:literature-review}..."} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

## Best Practices

<Tip>
  **Cross-referencing best practices:**

  1. **Consistent labeling**: Use standard prefixes and descriptive names
  2. **Non-breaking spaces**: Always use `~` before `\ref{}` commands
  3. **Meaningful labels**: Choose names that describe content, not position
  4. **Compile multiple times**: Run LaTeX twice to resolve all references
  5. **Use cleveref**: Automate reference types and formatting
  6. **Check broken refs**: Look for "??" in output indicating unresolved references
  7. **Hyperref last**: Load hyperref before cleveref but after most other packages
  8. **Backup strategy**: Keep label conventions documented for large projects
</Tip>

## Troubleshooting

<Warning>
  **Common cross-referencing issues:**

  1. **"??" in output**: Reference not found - check label spelling and compile twice
  2. **Wrong reference numbers**: Labels may have moved - recompile completely
  3. **Missing hyperlinks**: Ensure hyperref is loaded before cleveref
  4. **Broken subfigure refs**: Check subcaption package and label placement
  5. **cleveref not working**: Load after hyperref and other reference packages
  6. **External refs failing**: Ensure external documents compiled first
  7. **Theorem refs wrong**: Check theorem numbering and cleveref configuration
  8. **PDF bookmarks broken**: Check special characters in section titles
</Warning>

## Advanced Tips

### Conditional References

<LatexSource filename="conditional-references.tex" source={"\\usepackage{ifthen}\n\n% Check if reference exists\n\\newcommand{\\safecref}[1]{%\n  \\ifthenelse{\\equal{\\ref{#1}}{??}}{%\n    [Reference not found]%\n  }{%\n    \\cref{#1}%\n  }%\n}\n\n% Check if on same page\n\\newcommand{\\smartref}[1]{%\n  \\ifthenelse{\\equal{\\pageref{#1}}{\\thepage}}{%\n    \\cref{#1} above%\n  }{%\n    \\cref{#1} on page~\\pageref{#1}%\n  }%\n}\n\n% Usage\n\\smartref{fig:test}  % → \"figure 1 above\" or \"figure 1 on page 5\""} />

<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>

### Custom Reference Macros

<LatexSource filename="custom-ref-macros.tex" source={"% Define convenient macros\n\\newcommand{\\figref}[1]{Figure~\\ref{#1}}\n\\newcommand{\\tabref}[1]{Table~\\ref{#1}}\n\\newcommand{\\eqnref}[1]{Equation~\\eqref{#1}}\n\\newcommand{\\secref}[1]{Section~\\ref{#1}}\n\\newcommand{\\chapref}[1]{Chapter~\\ref{#1}}\n\n% Enhanced macros with page references\n\\newcommand{\\figpref}[1]{Figure~\\ref{#1} on page~\\pageref{#1}}\n\\newcommand{\\tabpref}[1]{Table~\\ref{#1} on page~\\pageref{#1}}\n\n% Usage\n\\figref{fig:results} shows...      % → Figure 1 shows...\n\\tabpref{tab:data} contains...     % → Table 1 on page 3 contains..."} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt is part of a multi-pass cross-reference or bibliography workflow. A trustworthy final page requires the surrounding project and its auxiliary files, so this standalone code box documents the workflow without claiming a complete rendered result.
  </Info>
</RenderedOutput>

## Quick Reference

### Essential Commands

| Command          | Purpose               | Example Output       |
| ---------------- | --------------------- | -------------------- |
| `\label{name}`   | Create label          | (invisible)          |
| `\ref{name}`     | Reference number      | 1, 2, 3...           |
| `\pageref{name}` | Reference page        | 5, 10, 15...         |
| `\eqref{name}`   | Equation reference    | (1), (2), (3)...     |
| `\cref{name}`    | Smart reference       | figure 1, table 2... |
| `\Cref{name}`    | Capitalized reference | Figure 1, Table 2... |

### Compilation Order

```bash theme={null}
# Standard compilation for references
pdflatex document.tex
pdflatex document.tex

# With bibliography
pdflatex document.tex
biber document      # or bibtex document
pdflatex document.tex
pdflatex document.tex
```

***

<Info>
  **Next**: Learn about [Package management](/learn/latex/package-management) to understand how to find, install, and use LaTeX packages effectively.
</Info>
