2

In the code posted below, I am using varwidth to shrink my tcolorbox to the text width for short text lines. However, I also have some wraparound text lines and the tcolorbox is too big in that case. How can I retain the shrink-to-fit behavior on short text snippets while changing the maximum margins of the tcolorbox? I would like the maximum margins of the gray area to be slightly less than the regular paragraph margins on both sides, but I also want to keep is shrinking to fit when the text length is smaller than that.

enter image description here

\documentclass[preprint]{revtex4-2} 
\usepackage{lipsum} 
\usepackage{setspace}  
\usepackage{varwidth} 
\usepackage{tcolorbox}

\tcbuselibrary{breakable}

\newsavebox{\myboxbox}
\NewDocumentEnvironment{mybox}{+b}% find a better name
{%
    \centering
    \setlength{\parindent}{0pt}%
    % measure the text width
    \sbox{\myboxbox}{\begin{varwidth}{\columnwidth}#1\end{varwidth}}%
    \begin{tcolorbox}[
        breakable,
        width=\dimexpr\wd\myboxbox+8mm,
        top=3mm,
        bottom=4mm,
        ]
        #1
    \end{tcolorbox}%
}{}

\begin{document}


\lipsum[1]\\

\begin{mybox}
    \begin{singlespace}
    \lipsum[1]
    \end{singlespace}
\end{mybox}


\begin{mybox}
    \begin{singlespace}
        Just a few words here.  Just a few words here.
    \end{singlespace}
\end{mybox}



\end{document}

2

Set the varwidth to \dimexpr\columnwidth-8mm to subtract off what you later add back to the width of the tcolorbox.

\documentclass[preprint]{revtex4-2} 
\usepackage{lipsum} 
\usepackage{setspace}  
\usepackage{varwidth} 
\usepackage{tcolorbox}

\tcbuselibrary{breakable}

\newsavebox{\myboxbox}
\NewDocumentEnvironment{mybox}{+b}% find a better name
{%
    \centering
    \setlength{\parindent}{0pt}%
    % measure the text width
    \sbox{\myboxbox}{\begin{varwidth}{\dimexpr\columnwidth-8mm}#1\end{varwidth}}%
    \begin{tcolorbox}[
        breakable,
        width=\dimexpr\wd\myboxbox+8mm,
        top=3mm,
        bottom=4mm,
        ]
        #1
    \end{tcolorbox}%
}{}

\begin{document}


\lipsum[1]\\

\begin{mybox}
    \begin{singlespace}
    \lipsum[1]
    \end{singlespace}
\end{mybox}


\begin{mybox}
    \begin{singlespace}
        Just a few words here.  Just a few words here.
    \end{singlespace}
\end{mybox}



\end{document}

enter image description here

1
  • Thanks! You are really cool! – hodop smith Mar 25 at 19:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.