19

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.

Kazark
  • 779
Rectifier
  • 765

3 Answers3

18

You could load the xcolor package and use that package's \colorbox macro. The argument of \colorbox can be both text and math material.

enter image description here

\documentclass{article}
\usepackage[svgnames]{xcolor} % for 'lightgray' color
\begin{document}
\colorbox{lightgray}{word}

\colorbox{yellow}{abcde}

\colorbox{lime}{$a^2+b^2=c^2$}
\end{document}
Mico
  • 506,678
17

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};}
Ubiquitous
  • 2,566
9

One way could be the soulpos package that support line breaks:

mwe

\documentclass{article}
\usepackage[paperwidth=80mm, paperheight=20mm]{geometry}
\usepackage{xcolor}
\usepackage{soulpos}
\ulposdef{\hlc}[xoffset=1pt]{\mbox{\color{cyan!30}\rule[-.8ex]{\ulwidth}{3ex}}}
\begin{document}
Some math \hlc{$x^2+4$} and \hlc{some wonderfull text}. 
Need \hl{two} compilations.
\end{document}
Fran
  • 80,769
  • 1
    Here http://petr.olsak.net/opmac-tricks-e.html#coltext is another macro for hyphenated background-colored text. It needs not two compilations. – wipet Nov 06 '15 at 16:51