I'm trying to highlight text using the \texttt font and a background color (pretty much like the highlighting on StackExchange [i.e., this]. I already tried it using a colorbox, it doesn't support line breaks though, resulting in:

enter image description here

Alternatively, I found a package called soul for highlighting, but in my opinion it's visually not as appealing as the colorbox because of the missing padding, it will look like this:

enter image description here

On the left is the colorbox, on the right is the soul package.

My coding:


\definecolor{lightgrey}{rgb}{0.925, 0.925, 0.925}


Any ideas how to overcome these caveats?

UPDATE: As mentioned in the comments below \texttt doesn't support line breaks as well which makes the problem even worse.

  • Since \texttt{} does not break anyway, this is twice worsed idea to use \colorbox and \texttt – user31729 Mar 4 '16 at 11:57
  • @ChristianHupfer Thank you for this hint. But, so what do you recommend if I want that font, a background color with nice padding/margin and correct line breaking? – ScientiaEtVeritas Mar 4 '16 at 14:25

Soul doesn't support adjusting the sizes that determine the placement of its highlight box.

By looking at its code, I redefined one of its internal macros. I also used the trick from this answer.

\usepackage{tikz} % only to get \foreach

\definecolor{lightgrey}{rgb}{0.925, 0.925, 0.925}

    \setul{}{3.5ex}% increased by 1ex
    \dimen@i=-.75ex % increased by -0.25ex


    \foreach \i in {1,...,10} {
        text text text text text \codebox{extracalifragilisticexpealidocious}


Note that this may break if the authors of soul change their packet's interna and that the large boxes change the line height.

| improve this answer | |
  • Wow, what a hack. :) But it changes the font family of the text that is followed by the codebox to the ttfamily. If you try something like this: \codebox{extracalifragilisticexpealidocious} test test test test test test test – ScientiaEtVeritas Mar 8 '16 at 9:04
  • @ScientiaEtVeritas: You're right, I didn't properly test my code. I've added a TeX group in the \codebox command to fix this issue. Also note that this command enables hyphenation in all \ttfamily text. The linked question has a solution that fixes the issue. – wrtlprnft Mar 8 '16 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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