[Tex/LaTex] How to produce a tight box with a fancy border

mdframedtikz-pgf

I'd like to be able to typeset a tightly-boxed formula with a fancy border.

My progress so far has been to produce a box (with mdframed) with the fancy border I want (with tikz), but instead of being tight around its contents, it always extends to the width of the line.

\documentclass{beamer} 

\mode<presentation>
\usetheme{Madrid}

\usepackage[framemethod=tikz]{mdframed}
\usepackage{tikz}
\usetikzlibrary{decorations.markings}

% Caution-tape frame style
\mdfdefinestyle{caution}{linewidth=10pt,
  tikzsetting={decorate,decoration={markings,
      mark=between positions 0 and 1 step 6pt
      with { 
        \fill[yellow] (-3pt,-2pt) -- (0pt,-2pt) -- (3pt,2pt) -- (0pt,2pt) -- (-3pt,-2pt);
        \fill[black] (0pt,-2pt) -- (3pt,-2pt) -- (6pt,2pt) -- (3pt,2pt) -- (0pt,-2pt);
}}}}

\begin{document}

\begin{frame}{testing}

  \begin{mdframed}[style=caution]
    $\frac{d}{dx} x^2 = 2x$
  \end{mdframed}

\end{frame}

\end{document}

enter image description here

I am not sure if mdframed is capable of drawing a tight box. If it is, I would appreciate any pointer to the right incantation. If not, I am in need of an alternative. I have looked at the empheq package, which allows a custom "box command" to be specified, but I am at a loss about how to translate my fancy border code into the form it wants.

Additionally, I'd like for it to be possible for the box to be embedded in a line of text, like:

\begin{frame}{testing}
My cool equation is \begin{foo}$\frac{d}{dx} x^2 = 2x$\end{foo}, isn't it neat?
\end{frame}

Best Answer

I can provide a solution which uses the packages environ and varwidth. Putting the mdframed into a minipage prevents it from taking up the whole line, so it can be embedded into other text.

enter image description here

\documentclass{beamer} 

\mode<presentation>
\usetheme{Madrid}
\usepackage{calc}
\usepackage[framemethod=tikz]{mdframed}
\usepackage{tikz}
\usetikzlibrary{decorations.markings}

% Caution-tape frame style
\mdfdefinestyle{caution}{linewidth=10pt,
  tikzsetting={decorate,decoration={markings,
      mark=between positions 0 and 1 step 6pt
      with { 
        \fill[yellow] (-3pt,-2pt) -- (0pt,-2pt) -- (3pt,2pt) -- (0pt,2pt) -- (-3pt,-2pt);
        \fill[black] (0pt,-2pt) -- (3pt,-2pt) -- (6pt,2pt) -- (3pt,2pt) -- (0pt,-2pt);
}}},
innerleftmargin=5pt,innerrightmargin=5pt,align=center,nobreak,
}

\usepackage{environ,varwidth}
\newsavebox\MyTempBox
\NewEnviron{caution}{%
\savebox\MyTempBox{%
\begin{varwidth}{\linewidth}
\BODY
\end{varwidth}}%
\begin{minipage}{\dimexpr\wd\MyTempBox+12pt\relax}
\begin{mdframed}[style=caution,userdefinedwidth=\dimexpr\wd\MyTempBox+12pt\relax]
\BODY
\end{mdframed}%
\end{minipage}
}%




\begin{document}

\begin{frame}{testing}
My cool equation is \begin{caution}$\frac{d}{dx} x^2 = 2x$\end{caution}, isn't it neat?
\end{frame}

\end{document}