[Tex/LaTex] Shaded box around multiline section heading

titlesec

I'm using LaTeX to write up an assignment which comprises a number of questions. I'd like to break up the questions from my answers by placing the section headings inside a shaded box. I'm relatively new to LaTeX.

So far, from searching around and reading quite a few examples, I've managed to knock together something of a partial solution (attempted minimal working example here:)

\documentclass{article}
\usepackage{titlesec}
\usepackage{lipsum}
\usepackage[framemethod=TikZ]{mdframed}
\usepackage{tikz}\usetikzlibrary{shapes.misc}
\newcommand\qnhead{%
\tikz[baseline,trim left=3.1cm, trim right=3cm] {
        \fill [black!12] (0.5cm,-1ex) rectangle (\textwidth+3.3cm,2.5ex);
        \node [
            anchor= base east,
            rectangle,
            minimum height=3.5ex] at (3cm,0ex) {
    \textnormal{\textbf{Question \thesection}}
};
}}
\titleformat{\section}{\itshape\large}{\qnhead}{0.1cm}{}
\renewcommand{\thesection}{\arabic{section}}

\begin{document}
\section{The text of the first question, which spans over more than %
         one line, will be placed here.}
\lipsum[2]
\section{The second question text will be placed here.}
\lipsum[2]
\end{document}

This works great until I have a question that ends up spanning over multiple lines. It's a limitation, I think, of the way I've got tikz drawing the rectangle, but I can't work out how to modify the code to make it span multiple lines.

Does anyone have any suggestions as to how I would go about fixing this?

enter image description here

Best Answer

I propose a different approach: to use the mdframed and amsthm packages to define a theorem-like environment, so you don't have to change the meaning of \section. Something along the following lines:

\documentclass{article}
\usepackage{amsthm}
\usepackage[framemethod=TikZ]{mdframed}
\usepackage{lipsum}

\newlength\Questionwd
\setlength\Questionwd{2.8cm}
\newlength\Innerlsep
\setlength\Innerlsep{3pt}

% definition of the theorem style
\newtheoremstyle{mystyle}
  {\topsep}{\topsep}
  {\large\itshape%
    \parshape 2 0cm \linewidth \dimexpr\Questionwd-3pt\relax\dimexpr\linewidth-\Questionwd+3pt\relax%
  }
  {}{\bfseries}{}{0em}
  {\makebox[\dimexpr\Questionwd-\Innerlsep\relax][l]{%
    \thmname{#1}~\thmnumber{#2}\hfill}%
  }

% we use the previously defined style for the definition of the new theorem environment
% built with the mdframed package
\theoremstyle{mystyle}
\newmdtheoremenv[
  leftmargin=-\Questionwd,
  rightmargin=-8pt,
  innerleftmargin=\Innerlsep,
  linecolor=black!12,
  backgroundcolor=black!12,
  skipabove=0.65cm,
  skipbelow=0.20cm
]{question}{Question}

\begin{document}

\begin{question}
The text of the first question, which spans over more than one line, will be placed here.
\end{question}
\lipsum[2]
\begin{question}
The second question text will be placed here.
\end{question}
\lipsum[2]

\end{document}

enter image description here

Related Question