CSS Colors
If you've worked in any sort of UI development, you've probably seen colors defined in RGB notation. RGB notation refers to "how much" red, green, and blue is present in a particular color. For those unfamiliar with color theory, any color can be produced by mixing varying amounts of red, green, and blue.
rgb ( [0-255], [0-255], [0-255] )
│ │ └────────── blue
│ └───────────── green
└───────────────── red
The amount of each primary color can be any number in the range of 0-255
.
For example, rgb(255, 0, 0)
denotes a color that has the most
amount of red possible, no greens, and no blues. So rgb(255, 0, 0)
represents the "purest" red possible. rgb(0, 0, 0)
means the absence of any
primary colors, which in other words denotes black. Conversely,
rgb(255, 255, 255)
means the maximum amount of all primary colors,
which is the same as white.
Does the number 255
remind you of anything? Whenever you see 255
,
you should automatically think of 1 byte or 8 bits. 1 byte has eight
binary digits, each of which can have two possible values: 0
or 1
.
This means that 1 byte can store a maximum of 2^8 = 256
values,
or in our case the values of 1-255
plus 0
. Another way of thinking about it is that when you have
8 bits and all of them are "on" (i.e. "11111111"
), you have the maximum quantity that can be
represented in 8 bits, which is 255
.
1 1 1 1 1 1 1 1
2⁷ + 2⁶ + 2⁵ + 2⁴ + 2³ + 2² + 2¹ + 2⁰
= 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1
= 255
This implies that we can store the amount of each primary color in 1 byte, or the entire RGB value in 3 bytes. In fact, colors are usually stored in 4 bytes to make it an even number. The 4th bit represents the amount of transparency in the color. When transparency is included in the color definition, the notation is called RGBA. "A" is short for the alpha channel for transparency.
rgba ( [0-255], [0-255], [0-255], [0-255] )
│ │ │ └─ 1 byte for transparency
│ │ └────────── 1 byte for blue
│ └─────────────────── 1 byte for green
└──────────────────────────── 1 byte for red
= 4 bytes in total to represent a color