It is much more complicated for the browser to obtain the encoding of the CSS document than that of the HTML document. The places where the encoding can be set include the Content-type field of the ResponseHeader, the charset attribute of the link tag, the CSS document, and finally there is a default encoding document.
What will happen if the encoding recognition of a css document is wrong? English characters can be recognized normally, but Chinese characters will be displayed as garbled characters. This is mainly because Chinese fonts are used. The Chinese font displayed on the page is English font (the content is still Chinese, I mean the displayed font changes).
According to the CSS 2.1 specification [1], the following precedence is used to determine the encoding of an external CSS file:
1. The encoding specified by the "charset" parameter in the "Content-Type" field in the HTTP response header.
2. BOM and/or encoding defined by @charset.
3.<link charset="">
or encoding specified by the metadata provided by other linking mechanisms (if any).
4. The code defined in the HTML or another CSS file (if any) that imports the CSS file.
5. If the above steps fail to determine the encoding, it is assumed to be UTF-8.
Here is a method to get the encoding from bom (C#):
/// <summary> /// 从字节流判断编码(返回null是不能判断出编码) /// </summary> /// <param name="bt">输入字节流</param> /// <returns></returns> internal static string GetEncodingByByte(byte[] bt) { //带BOM的utf-8 var utf8 = new byte[] { 0xEF, 0xBB, 0xBF }; if (bt[0] == utf8[0] && bt[1] == utf8[1] && bt[2] == utf8[2]) { return "utf-8"; } //UTF-32-BE var utf32Be = new byte[] { 0x00, 0x00, 0xFE, 0xFF }; if (bt[0] == utf32Be[0] && bt[1] == utf32Be[1] && bt[2] == utf32Be[2] && bt[3] == utf32Be[3]) { return "utf-32"; } //UTF-32-LE var utf32Le = new byte[] { 0xFF, 0xFE, 0x00, 0x00 }; if (bt[0] == utf32Le[0] && bt[1] == utf32Le[1] && bt[2] == utf32Le[2] && bt[3] == utf32Le[3]) { return "utf-32"; } //UTF-32-2143 var utf322143 = new byte[] { 0x00, 0x00, 0xFF, 0xFE }; if (bt[0] == utf322143[0] && bt[1] == utf322143[1] && bt[2] == utf322143[2] && bt[3] == utf322143[3]) { return "utf-32"; } //UTF-32-3412 var utf323412 = new byte[] { 0xFE, 0xFF, 0x00, 0x00 }; if (bt[0] == utf323412[0] && bt[1] == utf323412[1] && bt[2] == utf323412[2] && bt[3] == utf323412[3]) { return "utf-32"; } //UTF-16-BE var utf16Be = new byte[] { 0xFE, 0xFF }; if (bt[0] == utf16Be[0] && bt[1] == utf16Be[1]) { return "utf-16"; } //UTF-16-LE var utf16Le = new byte[] { 0xFF, 0xFE }; if (bt[0] == utf16Le[0] && bt[1] == utf16Le[1]) { return "utf-16"; } return null; }