使用“clip title=false”可使 tcolorbox 长标题位于一行中。但是,tcolorbox 本身的宽度仍然适合内容。如何使 tcolorbox 宽度适合位于一行中的长标题的自然宽度(不换行)?
\documentclass[]{article}
\usepackage[skins,listings,breakable,listingsutf8,theorems,hooks,fitting]{tcolorbox}
\usepackage{calc}
\newtcbox{\LongTitleBox}[1][]{enhanced,title=\mbox{Title Larger than the Box Content},clip title=false,colbacktitle=white,coltitle=black,#1}%
\newtcbox{\LongTitleBoxResult}[1][]{enhanced,title=\mbox{Final Result},clip title=false,colbacktitle=white,coltitle=black,#1}%
\begin{document}
\LongTitleBox{Box Content}
\LongTitleBoxResult{1}
\LongTitleBoxResult{123 456 789}
\end{document}
答案1
这是一个有趣的问题。我的解决方案建议将标题隐藏在框内容中。因此,框的大小根据标题宽度和内容宽度的最大值来确定。请注意,如果对标题和框内容应用不同的字体,此解决方案就会失效(但这可以轻松适应)。
\documentclass[]{article}
\usepackage[skins]{tcolorbox}
\tcbset{longtitle/.style={%
title={#1},
before upper={\begin{tabular}{@{}l@{}}\phantom{#1}\\[\the\dimexpr-\ht\strutbox-\dp\strutbox]},
after upper={\end{tabular}}}}
\newtcbox{\LongTitleBox}[1][]{enhanced,longtitle={Title Larger than the Box Content},colbacktitle=white,coltitle=black,#1}%
\newtcbox{\LongTitleBoxResult}[1][]{enhanced,longtitle={Final Result},colbacktitle=white,coltitle=black,#1}%
\begin{document}
\LongTitleBox{Box Content}
\LongTitleBoxResult{1}
\LongTitleBoxResult{123 456 789}
\LongTitleBoxResult{123 456 789 012}
\end{document}
答案2
正如 Thomas F. Sturm 所言,“如果标题和框内容使用不同的字体,此解决方案就会失效”。以下是 Thomas F. Sturm 解决方案的“一个”简单改编:
\usepackage[skins]{tcolorbox}
\def\TitleFontSize{\scriptsize}
\def\ContentFontSize{\huge}
\tcbset{longtitle/.style={title={#1},before upper={\begin{tabular}{@{}l@{}}\phantom{#1}\\[\the\dimexpr-\ht\strutbox-\dp\strutbox]},after upper={\end{tabular}}}}
\tcbset{longtitleDifferentSize/.style={title={#1},before upper={\begin{tabular}{@{}l@{}}\phantom{\TitleFontSize #1}\\[\the\dimexpr-\ht\strutbox-\dp\strutbox]},after upper={\end{tabular}}}}
\newtcbox{\LongTitleBoxPhantomFontSameSizeAsTitleFont}[1][]{enhanced,longtitleDifferentSize={Title Larger than the Box Content},fonttitle=\TitleFontSize,colbacktitle=white,coltitle=black,fontupper=\ContentFontSize, #1}%
\newtcbox{\LongTitleBoxPhantomFontSameSizeAsContentFont}[1][]{enhanced,longtitle={Title Larger than the Box Content},fonttitle=\TitleFontSize,colbacktitle=white,coltitle=black, fontupper=\ContentFontSize,#1}%
\begin{document}
\LongTitleBoxPhantomFontSameSizeAsTitleFont{Box Content}
\LongTitleBoxPhantomFontSameSizeAsContentFont{Box Content}
\end{document}