Why does HTML think “chucknorris” is a color?

后端 未结 9 1925
醉梦人生
醉梦人生 2020-11-22 05:07

How come certain random strings produce colors when entered as background colors in HTML? For example:

相关标签:
9条回答
  • 2020-11-22 05:39

    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>

    0 讨论(0)
  • 2020-11-22 05:42

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 05:43

    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:

    • make the string a length that is a multiple of 3 by adding 0s: chucknorris0
    • separate the string into 3 equal length strings: chuc knor ris0
    • truncate each string to 2 characters: ch kn ri
    • keep the hex values, and add 0's where necessary: 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.

    0 讨论(0)
提交回复
热议问题