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