How to create command for a box where text inside the box can automatically adjust?

A possible solution using the varwidth package:

\documentclass{article}
\usepackage{varwidth}
\usepackage{lipsum}% just to generate text for the example

\newcommand\mybox[2][\dimexpr\textwidth-2\fboxsep\relax]{%
\fbox{\begin{varwidth}{#1}
#2
\end{varwidth}}}

\begin{document}

\noindent\mybox{test}

\noindent\mybox{some longer text}

\noindent\mybox{text here text here text here text here text here}

\noindent\mybox{\lipsum[2]}

\end{document}

enter image description here

If my command is always meant to start and end its own paragraph, then the definition can be changed to something like

\newcommand\mybox[2][\dimexpr\textwidth-2\fboxsep\relax]{%
\par\noindent\fbox{\begin{varwidth}{#1}
#2
\end{varwidth}}\par}

and then one can simply say

\mybox{text text text text text}

If you are satisfied with a plain box then this is probably not the solution for you. To illustrate that the basic case works:

enter image description here

But of course, being a tikz solution you can style the boxes. Here are just a few of the many options that are avilaable:

enter image description here

Furthermore, by adding the option text width=\linewidth, you can chose to have the box take up the full \linewidth:

enter image description here

Code:

\documentclass{article}
\usepackage{tikz}
\usepackage{xparse}
\usepackage{lipsum}

\newlength{\LengthOfText}
\newlength{\LengthOfTextExceedingLineWidth}
\newlength{\TextWidth}
\newcommand{\Boxed}[2][]{%
    % #1 = box draw/fill options
    % #2 = text
    \settowidth{\LengthOfText}{\mbox{#2}}%
    \pgfmathsetlength{\LengthOfTextExceedingLineWidth}
        {\LengthOfText-\linewidth}
    \pgfmathsetlength{\TextWidth}{\LengthOfTextExceedingLineWidth > 0pt ? \linewidth : \LengthOfText}%
    \begin{tikzpicture}[baseline, inner sep=2pt, outer sep=0]
            \node [, text width=\TextWidth, #1] (Origin) {#2};
            \draw [thick, draw=black, #1] 
                (Origin.south west) rectangle (Origin.north east) ;
    \end{tikzpicture}%
}


\begin{document}
\noindent\Boxed{test}\par\medskip\noindent
\noindent\Boxed{some longer text}\par\medskip\noindent
\noindent\Boxed{text here text here text here text here text here}\par\medskip\noindent
\noindent\Boxed{\lipsum[2]}

\bigskip\noindent
\Boxed[red]{test}\par\medskip\noindent
\Boxed[dashed]{text here text here text here text here text here}\par\medskip\noindent
\Boxed[fill=yellow!20, fill opacity=0.3, text opacity=1]{\lipsum[2]}

\bigskip\noindent
\Boxed[blue, text width=\linewidth]{test}\par\medskip\noindent
\Boxed[draw=brown, text width=\linewidth]{text here text here text here text here text here}\par\medskip\noindent
\end{document}

Tags:

Boxes

Errors