# Center a Listing on page [duplicate]

I am trying to center a listing horizontally within a page.

So far I have tried defining the following macro:

``````\lstnewenvironment{snippet}[1][]
{\centering \lstset{float=htpb,#1}}
{}
``````

But it did not work.

I have read this question and answer, but I would prefer a solution that does not rely in figures or tables.

-

## marked as duplicate by Jubobs, Werner, Martin Schröder, mafp, JesseJan 16 '14 at 3:36

only possible when you define a width for a minipage:

``````\lstnewenvironment{snippet}[1][]
{\hfill\lstset{frame=single,#1}\minipage{0.6\linewidth}}
{\endminipage\hfill\null}
``````
-
Your suggestion is ot working, it gives a `! Emergency stop.` error and the resulting file does not contain the listing. –  Tiago Veloso Feb 5 '11 at 15:39
@Tiago: than give me a minimal example, which shows this error. For me it works! –  Herbert Feb 5 '11 at 16:42

If you set the line width i.e. `\lstset{linewidth=0.6\textwidth}`and want that centered, you can use margins instead. i.e.:

``````\lstset{linewidth=\textwidth,
xleftmargin=0.2\textwidth,
xrightmargin=0.2\textwidth}
``````

I usually use this method, but I haven't tried with the float= setting.

-