[Tex/LaTex] How to control the dimensions of \colorbox

colorbox

I want a long narrow horizontal colored rectangle, something more like a thick line, but I cannot get the height below a certain amount. The best I can come up with is:

\documentclass[11pt]{book}
\usepackage{color}
\begin{document}
xxxxx\colorbox{red}{%
\phantom{------------------}
}%
xxxxx 
\end{document}

where the number of - controls the length but I would like at most half the height of:

enter image description here

I have tried various solutions proposed for questions about height of boxes but was not able to find anything that did it. Did I miss anything?

Best Answer

The problem is that the - is sits an box with white space around it. You can see this by writing

\setlength{\fboxsep}{0pt}
\fbox{-}

which produces

Sample dash

indicating the box containing the dash sits on the baseline and rises to the height of a capital letter. (Actually --- is producing a different glyph, but the same considerations apply.) To get better control use a \rule. The syntax is

\rule[2pt]{3cm}{1.5ex}

to produce a rule of width 3cm, height 1.5ex all raised 2pt above the baseline. In your case to fit with the x's \rule{2cm}{1ex} should suffice, since 1ex is the nominal height of x in the font, but there are some optical effects from the serifs, so I suggest

\rule[-0.05ex]{2cm}{1.1ex}

As this is the actual shape you want to see you can enclose it in a simple \textcolor rather than having to make a phantom.

Sample output

\documentclass[11pt]{book}

\usepackage{color}

\begin{document}

xxxxx\textcolor{red}{\rule[-0.05ex]{2cm}{1.1ex}}xxxxx

\end{document}
Related Question