[Tex/LaTex] Equal spacing for figures and listings

captionsfloatslistingsspacing

I want to include figures and listings in my document and I want them to have the same spacings to text and captions.

\documentclass[a4paper,12pt,openany,parskip,oneside,ngerman,headsepline]{scrbook}
\usepackage{float}
\usepackage{graphicx}
\usepackage{caption}
\captionsetup{font=small,labelfont=bf}
\usepackage{listings}
\lstset{captionpos=b,frame=single}

\begin{document}
Some text

\begin{lstlisting}
Some code
\end{lstlisting}

Some text

\begin{figure}[H]
    \includegraphics[width=\textwidth]{image.png}
    \caption{Some caption}
    \label{fig:test}
\end{figure}

Some rext
\end{document}

The result is following (I added boxes to show the spacing).

Spacings

  1. As you can see, the red boxes have the same spacing.
    How can I make the spacing start above/below the frame?

  2. The spacing below the figure is bigger than the listing.
    How can I make them the same?

Best Answer

When the caption is below the float contents, you can adjust the following caption parameters through \captionsetup:

  • aboveskip (space between the float contents and the caption)
  • belowskip (space after the caption)

The default values are, for scrbook class, aboveskip=10pt and belowskip=0pt. Also, a \baselineskip is added by default before the floating object and 1.2\baselineskip after it, IIRC.

The above settings don't work for listings. But you can similarly set these parameters for listings through \lstset:

  • abovecaptionskip (space between the float contents and the caption)
  • belowcaptionskip (space after the caption)
  • aboveskip (space between the float contents and the preceding text)
  • belowskip (space between the float contents and the following text)

So leaving figure parameters untouched and adding in your \lstset something like

abovecaptionskip=10pt,belowcaptionskip=0pt,aboveskip=\baselineskip,belowskip=1.2\baselineskip

should do what you want.

Complete code

\documentclass[a4paper,12pt,parskip]{scrbook}
\usepackage{float}
\usepackage[demo]{graphicx} %option demo only for the example
\usepackage{caption}
\captionsetup{font=small,labelfont=bf}
\usepackage{listings}
\lstset{
  captionpos=b,
  frame=single,
  abovecaptionskip=10pt,
  belowcaptionskip=0pt,
  aboveskip=\baselineskip,
  belowskip=1.2\baselineskip
  }

\begin{document}
Some text

\begin{lstlisting}[caption={Some caption}]
Some code
\end{lstlisting}

Some text

\begin{figure}[H]
    \includegraphics[width=\textwidth]{image.png}
    \caption{Some caption}
    \label{fig:test}
\end{figure}

Some rext
\end{document} 

Output

enter image description here

You can adjust these values if you think they don't meet your needs.