24-Bit RGB Colors in ANSI Escape Codes#
Structure#
The 24-bit RGB color space represents a much broader array of colors. Simply use any number from 0
to 255
to set each of the red r
, green g
, and blue b
colors in the sequences 38;2;r;g;b
for text color and 38;2;r;g;b
for background color:
Code | Placement |
---|---|
\x1b[38;2;r;g;bm | Text |
\x1b[48;2;r;g;bm | Background |
Sequence Parts#
For example, the color code for light blue rgb(173, 216, 230)
can be broken down into the following parts:
Part | \x1b[ | 38;2; 48;2; | 173;216;230 | m |
---|---|---|---|---|
Description | Starts sequence, also called the Control Sequence Introducer (CSI). | Select foreground text or background color. | RGB color code where each number is between 0-255. | Ends sequence and calls the graphics function Select Graphic Rendition (SGR). |
Disclaimer
Not all terminals support 24-bit colors in RGB, HSL, or Hex. If your terminal does support such advanced colors, read on.
Examples#
For example, \x1b[38;2;142;194;21m
is a lime green foreground text color, and \x1b[48;2;194;21;139m
is a rosa background color. When wrapped with \x1b[0m
to reset the color, you can write this:
Python | |
---|---|
How it appears in the terminal:
% This is LIME GREEN text
% This is ROSA background
How to Use RGB Colors with Colorist
Instead of using raw ANSI escape codes, it's convenient to use Colorist to generate them while keeping the code readable.
Simply use the ColorRGB
class for foreground text colors or the BgColorRGB
class for background colors. For example:
Python | |
---|---|
How it appears in the terminal:
% This is LIME GREEN text
% This is ROSA background
In Colorist, the RGB color space is used to furthermore support definition of colors as HSL or Hex.