Colored box in new environment
The box has to be collected before typesetting it with a colored background:
\newsavebox{\selvestebox}
\newenvironment{colbox}[1]
{\newcommand\colboxcolor{#1}%
\begin{lrbox}{\selvestebox}%
\begin{minipage}{\dimexpr\columnwidth-2\fboxsep\relax}}
{\end{minipage}\end{lrbox}%
\begin{center}
\colorbox[HTML]{\colboxcolor}{\usebox{\selvestebox}}
\end{center}}
The lrbox
environment is very useful for this kind of business.
You don't have to guess the width (and px
is not the unit I would use); just remember that a padding of \fboxsep
is added to the contents of \colorbox
.
Now
\begin{colbox}{F8E0E0}
\textbf{Riddle: }\\ \textit{some text here}
\end{colbox}
will work. Notice how one can carry the argument to the "end part" of the environment, this is a standard technique.
To simplify the creation of such environments you can use a packages like framed
or environ
.
Example with framed
(this allows page breaks):
\newenvironment{colbox}{%
\def\FrameCommand{\colorbox{colboxcolor}}%
\MakeFramed{\advance\hsize-\width \FrameRestore}}
{\endMakeFramed}
and e.g.
\definecolor{colboxcolor}{HTML}{F8E0E0}
Then use:
\begin{colbox}
Text
\end{colbox}
Example with package environ
(no page break):
\NewEnviron{colbox}[1][\linewidth]{%
\colorbox{\colboxcolor}{%
\begin{minipage}{#1}
\BODY
\end{minipage}%
}
}
As stated in for very related question \newenvironment issues with environment comment such boxes can be done quite easily with the adjustbox
package. The technical solution is basically the same as in egreg's answer but with a much nicer and more flexible user interface.
You can adjust the margin with the margin
key and set the background color with bgcolor
which uses similar code like \colorbox
. You need to load xcolor
by yourself for this.
\documentclass{article}
\usepackage{xcolor}
\usepackage{adjustbox}
\newenvironment{colbox}[2]{%
\begin{adjustbox}{minipage=[b]{380px},margin=1ex,bgcolor=#1,env=center}% or use `bgcolor={HTML}{#1}` if you want to force HTML colors
\textbf{#2}\\
}{%
\end{adjustbox}%
}
\begin{document}
\begin{colbox}{green}{Riddle me this, Batman:}
What is ....
\end{colbox}
\begin{colbox}{{HTML}{F8E0E0}}{Riddle 2:}
What is ....
\end{colbox}
\end{document}