Center Latex lstlisting

43,134

Solution 1

Instead of using linewidth you should consider to use xleftmargin and xrightmargin (cf. texdoc listings, Chapter 4.10). The following code works without any center or minipage environment:

\lstset{
  caption=Descriptive Caption Text, 
  basicstyle=\footnotesize, frame=tb,
  xleftmargin=.2\textwidth, xrightmargin=.2\textwidth
}
\begin{lstlisting}
    printf("this should be centered!");
\end{lstlisting}

Solution 2

Your caption is actually centered over the listing. You are just making the lines that run along the top and bottom of your listing only 0.6\textwidth long. This makes it appear as if the caption was off-center. Also, your \centering doesn't center the listing (visible if you don't shorten the lines below and above).

This should work:

\begin{center}
  \lstset{%
    caption=Descriptive Caption Text,
    basicstyle=\ttfamily\footnotesize\bfseries,
    frame=tb
  }
  \begin{lstlisting}
    printf("this should be centered!");
  \end{lstlisting}
\end{center}

You don't explain why you want the delimiting lines to be 0.6\textwidth long. If you actually wanted to set the width of your listing to be that value, your approach doesn't do what you want. Use something like a minipage to set a width for the whole listing.

begin{minipage}{0.6\textwidth}
  \begin{center}
    \lstset{%
      caption=Descriptive Caption Text,
      basicstyle=\ttfamily\footnotesize\bfseries,
      frame=tb,
    }
    \begin{lstlisting}
      printf("this should be centered!");
    \end{lstlisting}
  \end{center}
\end{minipage}

Solution 3

Actually, what did work for me is the converse: putting the minipage inside the center environment.

Share:
43,134
Admin
Author by

Admin

Updated on October 12, 2020

Comments

  • Admin
    Admin over 3 years

    This is driving me crazy.

    I want to center a lstlisting in LaTeX.

    After 3 hours attempting here's some code:

    \lstset{ %
        caption=Descriptive Caption Text,
        label=lst:descr_capti_text,
        basicstyle=\ttfamily\footnotesize\bfseries,
        frame=tb,
        linewidth=0.6\textwidth
     }
    \centering\begin{tabular}{c}
    \begin{lstlisting}
    printf("this should be centered!");
    \end{lstlisting}
    \end{tabular}
    

    This is putting the lstlisting on the center but not its caption, that goes to the right. If I take out the tabular, then caption gets centered but the code goes to the left! :(

    Thank you.