Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I want to draw labels on a photograph. The labels will only contain 1..3 words, and sometimes there shall be a linebreak, e. g.

Big House \newline
(empty)

Is it possible to create a box which draws a white rectangle below this text and which adapts to the width of the text?

I could use \colorbox{white}{Big House \newline (empty)}, but it does not allow the linebreak.

If I use a \parbox{}, I have to define the width by hand.

Is there a box with a colored background, which can itself adapt its width to the longest text and contain linebreaks or paragraphs?

share|improve this question
add comment

2 Answers 2

up vote 7 down vote accepted

You could use the varwidth environment provided by the homonymous package; this environment is an analogue of minipage, but its resulting width is the natural width of its contents. A little example:

\documentclass{article}
\usepackage{varwidth}
\usepackage{xcolor}
\usepackage{lipsum}

\newcommand\MyCBox[1]{%
  \colorbox{red!60}{\begin{varwidth}{\dimexpr\linewidth-2\fboxsep}#1\end{varwidth}}}

\begin{document}

\noindent\MyCBox{Big House\\ (empty)}

\noindent\MyCBox{Big House and some more text\\ (empty)}

\noindent\MyCBox{Big\\ (empty)}

\noindent\MyCBox{\lipsum[1]}

\end{document}

enter image description here

share|improve this answer
    
\newcommand\MyCBox[1]{% \colorbox{red!60}{\begin{varwidth}{\dimexpr\linewidth-2\fboxsep}#1\end{varwidth}‌​}} While compiling we are getting the error as ! Undefined control sequence. <argument> \dimexpr Please suggest me how to avoid this error. –  CR20001 May 27 '13 at 5:39
add comment
\newcommand{\overbox}[2][l]{%
  \colorbox{white}{\begin{tabular}{@{}#1@{}}#2\end{tabular}}%
}

\overbox{Big House \\ (empty)}

One can also say

\overbox[c]{Big House \\ (empty)}

to get lines centered with respect to one another.

Example

enter image description here

share|improve this answer
    
very creative solution! Thanks! –  Martin Oct 26 '11 at 21:00
1  
You can also use {@{}c@{}} as the argument to tabular if you prefer centered lines. But see the edited answer for a slightly different approach. –  egreg Oct 26 '11 at 21:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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