How come certain random strings produce colors when entered as background colors in HTML? For example:
Most browsers will simply ignore any NON-hex values in your color string, substituting non-hex digits with zeros.
ChuCknorris
translates to c00c0000000
. At this point, the browser will divide the string into three equal sections, indicating Red, Green and Blue values: c00c 0000 0000
. Extra bits in each section will be ignored, which makes the final result #c00000
which is a reddish color.
Note, this does not apply to CSS color parsing, which follow the CSS standard.
<p><font color='chucknorris'>Redish</font></p>
<p><font color='#c00000'>Same as above</font></p>
<p><span style="color: chucknorris">Black</span></p>
The WHATWG HTML spec has the exact algorithm for parsing a legacy color value: https://html.spec.whatwg.org/multipage/infrastructure.html#rules-for-parsing-a-legacy-colour-value.
The code Netscape Classic used for parsing color strings is open source: https://dxr.mozilla.org/classic/source/lib/layout/layimage.c#155.
For example, notice that each character is parsed as a hex digit and then is shifted into a 32-bit integer without checking for overflow. Only eight hex digits fit into a 32-bit integer, which is why only the last 8 characters are considered. After parsing the hex digits into 32-bit integers, they are then truncated into 8-bit integers by dividing them by 16 until they fit into 8-bit, which is why leading zeros are ignored.
Update: This code does not exactly match what is defined in the spec, but the only difference there is a few lines of code. I think it is these lines that was added (in Netscape 4):
if (bytes_per_val > 4)
{
bytes_per_val = 4;
}
I'm sorry to disagree, but according to the rules for parsing a legacy color value posted by @Yuhong Bao, chucknorris
DOES NOT equate to #CC0000
, but rather to #C00000
, a very similar but slightly different hue of red. I used the Firefox ColorZilla add-on to verify this.
The rules state:
chucknorris0
chuc knor ris0
ch kn ri
C0 00 00
I was able to use these rules to correctly interpret the following strings:
LuckyCharms
Luck
LuckBeALady
LuckBeALadyTonight
GangnamStyle
UPDATE: The original answerers who said the color was #CC0000
have since edited their answers to include the correction.