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.
Centering. We center text or images using \begin{center} and \end{center}. Just put \begin{center} when you want to start centering, and \end{center} when you want to stop centering.
Referencing Code Listings\lstinputlisting[caption=Example C++, label={lst:listing-cpp}, language=C++]{code_sample. cpp} An example table can be seen in \ref{lst:listing-cpp}. Also note how the "Listing" prefix is automatically added within the document text whenever the reference is called.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With