The xcolor package
Provides colour for text, backgrounds and boxes: \textcolor, \colorbox, \definecolor, and mixtures written as blue!30.
Loading the package
\usepackage{xcolor}xcolor knows 19 colour names without options, among them red, blue, gray, orange and teal. A colour expression mixes them: blue!30 is 30 % blue on white, red!50!blue is half red and half blue. The expressions work wherever a colour name is expected, also in tikz and tcolorbox.
\definecolor creates colours of your own from RGB values or a hex code. The options dvipsnames, svgnames and x11names add ready-made names such as ForestGreen; the option table loads colortbl for coloured table cells.
Main commands
\textcolor{red}{text} | Colours the text in the second argument. |
{\color{blue} text} | Switches the colour until the group ends. |
\definecolor{brand}{HTML}{1F77B4} | Defines a colour from a hex code; the model RGB takes three values from 0 to 255. |
\colorlet{accent}{red!70!black} | Gives a name to a colour expression. |
\colorbox{yellow!40}{text} | Text on a coloured background. |
\fcolorbox{red}{white}{text} | Box with a frame colour and a background colour. |
\usepackage[dvipsnames]{xcolor} | Adds 68 colour names such as ForestGreen and RoyalBlue. |
Complete example
\documentclass{article}
\usepackage[dvipsnames]{xcolor}
\definecolor{brand}{HTML}{1F77B4}
\definecolor{soft}{RGB}{230,240,255}
\colorlet{accent}{red!70!black}
\begin{document}
\textcolor{brand}{Text in a colour defined by a hex code.}
{\color{ForestGreen} Green until the closing brace.} Black again.
\colorbox{soft}{Text on a light background}
\fcolorbox{accent}{yellow!20}{Text in a frame}
\textcolor{blue!30}{30\,\% blue},
\textcolor{red!50!blue}{red mixed with blue},
\textcolor{accent}{a named mixture}.
\end{document}Compiled with pdfLaTeX from TeX Live 2023.
Pitfalls
- A name that was never defined gives Undefined color `darkgreen'. The names are case-sensitive:
ForestGreenexists withdvipsnames,forestgreendoes not. - The model
rgbexpects values from 0 to 1,RGBvalues from 0 to 255.\definecolor{c}{rgb}{31,119,180}gives no error and the wrong colour. - Packages such as
tikzandbeamerloadxcolorthemselves. Before version 3 ofxcolor(November 2023), a later\usepackage[dvipsnames]{xcolor}then stopped with Option clash for package geometry.\PassOptionsToPackage{dvipsnames}{xcolor}before\documentclassworks in every version.
Related pages
- How-to Colored text in LaTeX
- How-to Highlight text in LaTeX
- How-to Color table rows, columns and cells in LaTeX
- Error Undefined color `darkgreen'
- Error Option clash for package geometry
- How-to Insert source code in LaTeX
- How-to Include source code from a file in LaTeX
- How-to Add a watermark in LaTeX
- How-to Draw a box around text in LaTeX
- How-to Change the format of section titles in LaTeX