TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have some code I want to typeset as verbatim (lstlisting would be ok as well) - but I want to highlight some parts of it via a different background color, i.e. something like this:

hello \colorbox{red}{world} blah
hello world blub

Where colorbox should not be interpreted verbatim and should not introduce additional horizontal spaces, i.e. blah and blub should be correctly aligned (like without any highlighting).

I tried the Verbatim and lstlisting environments like this:




in combination with a then escaped colorbox command - the highlighting works - but the additional spaces are introduced and screw up the character alignment.

How can I do it right?

share|improve this question
up vote 8 down vote accepted

I think the alltt environment from the package with the same name is better suited here. It makes everything verbatim except \,{ and }, similar to \begin{Verbatim}[commandchars=\\\{\}].

The mentioned added space is due to the used \fboxsep which makes the box bigger. You can avoid this by setting this value to zero, either globally or locally using a own macro. This however makes the box very tight on all four sites. An added \strut makes sure that it has always the same height and depth.

% Global:
% Better:
hello \colorbox{red}{world\strut} blah
hello world blub
hello \hi{world} blub

Another alternative, the best one IHMO, is to compensate for the fboxsep before and after the box:

% Compensate for fbox sep:
hello world blah
hello \Hi{world} blah



share|improve this answer
awesome answer! – maxschlepzig Feb 22 '11 at 22:06

Just set \fboxsep=0pt to reduce the extra space around \colorbox.

And here's another solution:


enter image description here

share|improve this answer

Your Answer


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.