LaTeX \caption\captionof 详解

\caption 只能在浮动体(figuretable)内使用,离开浮动体即报错。\captionofcaption 宏包提供,可在任意位置生成图表标题,无需依赖浮动体。两者对比如下。

1. \caption:浮动体专属

\caption 只能用在浮动体环境内部,最典型的是 figuretable

1
2
3
4
5
6
\begin{figure}[htbp]
\centering
\includegraphics[width=0.6\textwidth]{example.png}
\caption{这是一张示例图片}
\label{fig:example}
\end{figure}

浮动体会自动调整位置以达到最佳排版效果。\caption 依赖浮动体提供的计数器与编号机制,离开浮动体即无法工作。\caption 放在 \label 之前才能正确生成交叉引用编号。

2. \captionof:在非浮动体中使用标题

\captionofcaption 宏包提供,语法 \captionof{类型}{标题}

1
2
3
4
5
6
7
8
\usepackage{caption}   % 导言区加载

% 用法示例
\begin{center}
\includegraphics[width=0.5\textwidth]{photo.jpg}
\captionof{figure}{不使用 figure 浮动的图片}
\label{fig:photo}
\end{center}

典型适用场景

  • minipage 内并列图表:多个子图放在同一个 figure 中,每个 minipage 内用 \captionof 独立编号。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
\begin{figure}[htbp]
\centering
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[width=\textwidth]{a.png}
\captionof{figure}{子图 A}
\end{minipage}
\hfill
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[width=\textwidth]{b.png}
\captionof{figure}{子图 B}
\end{minipage}
\end{figure}
  • 不希望内容浮动:需要在文字中嵌入图表并固定位置时,用 \captionof 配合 center 即可(figure 环境会自动漂移)。
  • table 以外的表格:如用 tabular 直接写表格但不套 table 环境时。

提示:如果需要子图自动编号(a、b、c),推荐搭配 subcaption 包使用 \captionof{subfigure}{...}

3. 对比总结

特性 \caption \captionof
是否需要浮动体 必须(figure/table 不需要
是否需要 caption 宏包 不需要 需要
内容是否自动浮动 否(固定在当前位置)
适用环境 figuretable minipagecenter、任意位置
语法 \caption{标题} \captionof{类型}{标题}

4. 常见注意事项

  • **编译报错 “Not in outer par mode”**:在非浮动体环境使用了 \caption,换成 \captionof 并加载 caption 宏包即可。
  • \captionof 不会创建浮动体,所以 [htbp] 这样的位置参数对它没有意义——它永远停留在你放置的位置。
  • 编号计数器是共享的\captionof{figure}{...} 会递增 figure 计数器,和 \caption 保持统一编号序列。
  • subcaption 包内部已加载 caption,无需重复 \usepackage{caption}

5. 小结

有浮动体用 \caption,没浮动体用 \captionof\captionof 在任意位置给图表加编号标题,代价是放弃自动浮动排版。