Why does HTML think “chucknorris” is a color?

后端 未结 9 2034
醉梦人生
醉梦人生 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: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;
    }
    

提交回复
热议问题