# Auto width tcolorbox around equation

I am using tcolorbox to draw boxes around equations. Since the box widths are equal to the equation widths, long titles are often shrunk, hence looking ugly, as shown here:

Is there any way to draw a box of auto-width around the equation and title?

A minimal working example is here:

\documentclass[11pt]{article}
\usepackage[many]{tcolorbox}

\begin{document}
$$\tcbhighmath[title=A long title hence does not fit]{\lambda=at^2}$$

$$\tcbhighmath[title=short-title]{\lambda=at^2+bt^3}$$
\end{document}


A different approach by defining a new key autowidth title that lets the minimum text width to be equal to the the title length

\documentclass[11pt]{article}
\usepackage[many]{tcolorbox}

\pgfkeysdef{/tcb/autowidth title}{
\pgfmathwidth{"#1"}
\def\width{\pgfmathresult pt} % \width = title length
%
\tcbset{title=#1,
tcbox width=minimum center,
text width=\width % minimum text width = title length
}
}

\begin{document}
$$\tcbhighmath[autowidth title=A long title hence does not fit ]{\lambda=at^2}$$

$$\tcbhighmath[autowidth title=short-title]{\lambda=at^2+bt^3}$$

\end{document}


• My compliments for another answer. Very good and I have much appreciated it. – Sebastiano Jan 5 at 21:54

From this excellent macro of Thomas F. Sturm: ....fit the width...., here there is my adapt answer:

\documentclass[11pt]{article}
\usepackage[many]{tcolorbox}
\tcbset{longtitle/.style={%
title={#1},
before upper={\begin{tabular}{@{}l@{}l}\phantom{#1}\\[\the\dimexpr-\ht\strutbox-\dp\strutbox]},
after upper={\end{tabular}}}
}

\begin{document}
$$\tcbhighmath[longtitle=A long title hence does now fit]{\lambda=at^2}%<---- for a double dollar$$

$$\tcbhighmath[title=short-title]{\lambda=at^2+bt^3}%<---- without a double dollar$$
\end{document}


A fix for avoiding the $ characters in the main argument: \documentclass[11pt]{article} \usepackage{array} \usepackage[many]{tcolorbox} \tcbset{longtitle/.style={% title={#1}, before upper={%$\begin{array}{@{}>{\displaystyle}l@{}}
\mbox{\phantom{#1}}\\[\the\dimexpr-\ht\strutbox-\dp\strutbox]%
},
after upper={\end{array}\$}},
}

\begin{document}

$$\tcbhighmath[longtitle=A long title hence does now fit]{\lambda=at^2}$$

$$\tcbhighmath[title=short-title]{\lambda=at^2+bt^3}$$

\end{document}

• @egreg Thank you very much (Tks \to \infty) for your precious edit. – Sebastiano Jan 5 at 21:30