10

The following code does not align the lstlisting entirely to the top, but keeps some unwanted space between the page's top and the listing. How can I align the lstlisting to the very top?

\documentclass{memoir}

\usepackage{caption}
\usepackage{listings}
\usepackage{xcolor}
\usepackage[showframe]{geometry}
\usepackage{lipsum}

\DeclareCaptionFormat{nice}{\noindent\colorbox{blue!10}{\hspace{1em}#1#2#3\hspace{1em}}}

\begin{document}

\lstdefinestyle{interfaces}{
  float,
  floatplacement=tbp
}

\captionsetup[lstlisting]{format=nice,singlelinecheck=false,margin=3pt,font={bf,sf,footnotesize}}

\begin{lstlisting}[style=interfaces,caption={Caption.}]
interface Interface {
}
\end{lstlisting}

\lipsum[1]

\end{document}

enter image description here


Less code for showing the issue:

\documentclass{article}
\usepackage{listings}
\usepackage{showframe}
\usepackage{lipsum}

\begin{document}
    \begin{lstlisting}[
        float % toggle here
        ]
    Hello world
    \end{lstlisting}
    \lipsum[1]  
\end{document}
1
  • I will add a more minimal example to your post. Just roll it back. But this is showing better the actual problem. Don't know how to fix that. sorry.
    – LaRiFaRi
    Aug 12 '15 at 8:00
11

There is a hint on page 38 of the manual for the caption package:

Please note that the listings package has its very own options for controlling the position and the skips of the caption: captionpos=, abovecaptionskip=, and belowcaptionskip=. (See listings documentation for details.)

Trial and error shows that if you add

\lstdefinestyle{interfaces}{
  float=tp,
  floatplacement=tbp,
  abovecaptionskip=-5pt
}

to your MWE then you get what (I think) you want:

enter image description here

For completeness, here is the full MWE:

\documentclass{memoir}


\usepackage{listings}
\usepackage{xcolor}
\usepackage[showframe]{geometry}
\usepackage{lipsum}

\DeclareCaptionFormat{nice}{\noindent\colorbox{blue!10}{\hspace{1em}#1#2#3\hspace{1em}}}

\begin{document}

\lstdefinestyle{interfaces}{
  float=tp,
  floatplacement=tbp,
  abovecaptionskip=-5pt
}

\captionsetup[lstlisting]{format=nice,singlelinecheck=false,margin=3pt,
     font={bf,sf,footnotesize},skip=0pt}

\begin{lstlisting}[style=interfaces,caption={Caption.}]
interface Interface {
}
\end{lstlisting}

\lipsum[1]

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.