Put a grey background behind code extracts in a Latex document (like this site does)

The key backgroundcolor of the lstlisting is what you are looking for for the colored background. To indent a bit the code, play with xleftmargin and framexleftmargin to fit your needs.

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\begin{document}
Test

\begin{lstlisting}[backgroundcolor = \color{lightgray},
                   language = C,
                   xleftmargin = 2cm,
                   framexleftmargin = 1em]
#include <stdio.h>

int main(int argc, char ** argv)
{
  printf("Hello world!\n");
  return 0;
}
\end{lstlisting}
\end{document}

enter image description here


I've been playing around with different options and I found another way to do it. I'll add it here as an alternative suggestion.

This looks very similar to the style used on the stackexchange sites.

%Put in the header

\usepackage{listings} %code extracts
\usepackage{xcolor} %custom colours
\usepackage{mdframed} %nice frames

\definecolor{light-gray}{gray}{0.95} %the shade of grey that stack exchange uses

%Put in the main document

\begin{mdframed}[backgroundcolor=light-gray, roundcorner=10pt,leftmargin=1, rightmargin=1, innerleftmargin=15, innertopmargin=15,innerbottommargin=15, outerlinewidth=1, linecolor=light-gray]
\begin{lstlisting}
    #include <stdio.h>

    int main(int argc, char ** argv)
    {
      printf("Hello world!\n");
      return 0;
    }
\end{lstlisting}
\end{mdframed} 

Here's yet another solution using tcolorbox (version 3.02).

The first variant is breakable and uses the full line width:

\documentclass{article}
\usepackage{xcolor}
\usepackage[skins,listings,breakable]{tcolorbox}
\begin{document}

\begin{tcblisting}{breakable,listing only,
  listing options={language=c,aboveskip=0pt,belowskip=0pt},
  size=fbox,boxrule=0pt,frame hidden,arc=0pt,colback=lightgray}
#include <stdio.h>

int main(int argc, char ** argv)
{
  printf("Hello world!\n");
  return 0;
}
\end{tcblisting}

\end{document}

enter image description here

The second variant is not breakable, but the gray background adapts to the code width:

\documentclass{article}
\usepackage{xcolor}
\usepackage[skins,listings,breakable]{tcolorbox}
\begin{document}

\begin{tcblisting}{hbox,listing only,
  listing options={language=c,aboveskip=0pt,belowskip=0pt},
  size=fbox,boxrule=0pt,frame hidden,arc=0pt,colback=lightgray}
#include <stdio.h>

int main(int argc, char ** argv)
{
  printf("Hello world!\n");
  return 0;
}
\end{tcblisting}

\end{document}

enter image description here