[Tex/LaTex] Using \color inside a \parbox causes vertical displacement

boxescolorparbox

When modifying my answer to this question I came across some odd behaviour.
If \color{<color>} is used at the start of a top-aligned \parbox, then the entire box is moved downwards, like this:

\documentclass{article}
\usepackage{xcolor}
\begin{document}
Word
\framebox{\parbox[t]{1cm}{word}} %% <- this is fine
\framebox{\parbox[t]{1cm}{\textcolor{blue}{word}}} %% <- this is fine
\framebox{\parbox[t]{1cm}{\color{blue}word}} %% <- ??
\framebox{\parbox[t]{1cm}{\hskip0pt\color{blue}word}} %% <- this is fine
\framebox{\parbox[t]{1cm}{\leavevmode\color{blue}word}} %% <- this is fine
\framebox{\parbox[t]{1cm}{$\displaystyle\int$}} %% <- this is fine
\framebox{\parbox[t]{1cm}{\color{blue}$\displaystyle\int$}} %% <- ??
\end{document}

enter image description here

(The \frameboxes are just there to show the locations/sizes of the \parboxes.)

Can someone tell me why this happens (and how I can best avoid it)?

Best Answer

\color is usually implemented via "whatsits", i.e. \special or \pdfcolorstack in case of pdfTeX. It becomes the top element at the start of the vertical box (\parbox[t]). The following paragraph starts below. Putting it after \leavevmode at the baseline of the starting paragraph is the right fix.

For debugging, a box can be inspected by \showbox:

\documentclass{article}
\usepackage{color}
\begin{document}
  \showboxdepth=\maxdimen
  \showboxbreadth=\maxdimen
  \tracingonline=1
  \setbox0=\hbox{\parbox[t]{1cm}{\color{blue}word}}
  \showbox0
\end{document}

The console (with \tracingonline=1) and the .log file reports:

\hbox(0.0+6.94444)x28.45274
.\vbox(0.0+6.94444)x28.45274
..\pdfcolorstack 0 push {0 0 1 rg 0 0 1 RG}
..\glue(\parskip) 0.0
..\hbox(6.94444+0.0)x28.45274, glue set 7.03604fil
...\hbox(0.0+0.0)x0.0
...\OT1/cmr/m/n/10 w
...\kern-0.27779
...\OT1/cmr/m/n/10 o
...\OT1/cmr/m/n/10 r
...\OT1/cmr/m/n/10 d
...\penalty 10000
...\glue(\parfillskip) 0.0 plus 1.0fil
...\glue(\rightskip) 0.0
..\pdfcolorstack 0 pop

! OK.
l.8   \showbox0
Related Question