I try to highlight text with \texttt font and background color (somehow like the highlighting on StackExchange: this). I tried with a colorbox, but the problem is that it doesn't support line breaks, it will look like this:

enter image description here

Then I found a package called soul for highlighting, but in my opinion it's not that pretty like the colorbox because of missing padding / margin, it will look like this:

enter image description here

Left one is the colorbox, right one is the soul package.

My coding:


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


How to solve this problem? Thank you in advance.

UPDATE: As mentioned in the comments below \texttt doesn't support line breaks as well. So there is a double challenge to get what I want...

  • 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.