[Tex/LaTex] Grey highlighted words

color

How can I make small, grey-highlighted code – words just like this one in this sentence. Is it possible to put some math in these boxes later? I tried to use soul package but I didn't manage to change the colour.

Best Answer

The command to change the colour of a highlight in soul is \sethlcolor{}. Here's an MWE:

\documentclass{article}
\usepackage{xcolor,soul}
\sethlcolor{lightgray}
\begin{document}
\hl{this text has a light grey background}
\end{document}

You may encounter some trouble with mathematics in that the highlight does not expand vertically to fit the full height of your math; i.e. it looks like this:

enter image description here

A solution in this case would be to put your math into a Tikz node. The following code is an MWE in which I create a command \tikzhl that implements a highlight in this fashion:

\documentclass{article}
\usepackage{tikz}
\newcommand*{\tikzhl}[1]{\tikz[baseline=(X.base)] \node[fill=lightgray] (X) {#1};}
\begin{document}
\tikzhl{$x^2+4$}
\end{document}

The result looks like this:

enter image description here

Note that this Tikz solution (unlike soul) does not support line breaks. See How to "highlight" text/formulas with tikz? for more on implementing highlights with Tikz.

If you want the background to be a lighter shade of grey, change lightgray to black!10. Varying the number 10 between 0 and 100 will produce increasingly dark shades of grey.

In the Tikz solution, you can vary the amount of 'padding' around the edge of your text with the inner sep= option thus:

\newcommand*{\tikzhl}[1]{\tikz[baseline=(X.base)] \node[fill=black!10,inner sep=1pt] (X) {#1};}