[Tex/LaTex] Framed box with border inside margin

framed

I would like to use something like framed, but where the verticals borders are fully within the margins and the position and width of the actual content is unchanged, and with support for nesting the boxes. Is there any environment that supports this? Preferably without explicitly changing attributes for every level of nesting.

Best Answer

[Edit I mentioned in my first solution that there is a fancier way to do this, so here it is.]

I am assuming that by "the verticals borders are fully within the margins and the position and width of the actual content is unchanged" you mean that the nested boxes should have the same width as the outer boxes. If this is not the case then you just need to change the values of

leftmargin, rightmargin, innerleftmargin, innerrightmargin

in the code below. Modulo my awful choice of colours, I think that you are trying to achieve something like the following:

enter image description here

This was done using the mdframed package and the following code:

\documentclass{article}
\usepackage{mdframed}
\usepackage{xcolor}
\newcounter{FramedDepth}
\setcounter{FramedDepth}{-1}
\mdfdefinestyle{Framed}{linecolor=black,linewidth=0pt,leftmargin=0pt,rightmargin=0pt,
                        innerleftmargin=0pt,innerrightmargin=0pt}
\newenvironment{Framed}{%
  \addtocounter{FramedDepth}{1}
  \ifcase\theFramedDepth\def\FrameColour{blue!50}%
    \or\def\FrameColour{green!50}%
    \or\def\FrameColour{red!50}%
    \or\def\FrameColour{orange!50}%
    \fi%
  \begin{mdframed}[style=Framed,backgroundcolor=\FrameColour]%
}{\end{mdframed}\addtocounter{FramedDepth}{-1}}

\begin{document}

\begin{Framed}
  Some interesting text.
\end{Framed}

\begin{Framed}
  This is even more interesting.

    \begin{Framed}
      ...and this is beyond mentioning
    \end{Framed}
     Some more text
     \begin{Framed}
       Another level down
     \end{Framed}
  \end{Framed}
\end{Framed}

\end{document}

Personally, I prefer to have the nested boxes slightly indented. For example with

\mdfdefinestyle{Framed}{linecolor=black,linewidth=1pt}

you obtain:

enter image description here