在 HTML 中声明字符编码

Declaring character encodings in HTML

我应该这样声明字符集吗:

<meta http-equiv="content-type" content="text/html" charset="utf-8" />

或者像这样:

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

或者两者都有效?

这两个声明都是有效的,您总是可以使用简短的等效版本:

<meta charset="utf-8" /> 

希望对您有所帮助。

因为您以

开始文档
<!DOCTYPE html>

我怀疑是否有必要指定内容类型。而只是指定 encoding/charset:

<head>
   <meta charset="UTF-8">
</head>

根据@Alohci 的评论更新。

W3C's documentation on <meta http-equiv="...">:

encoding declaration state (http-equiv="content-type")

The encoding declaration state is just an alternative form of setting the charset attribute: it is a character encoding declaration. This state's user agent requirements are all handled by the parsing section of the specification.

For meta elements with an http-equiv attribute in the Encoding declaration state, the content attribute must have a value that is an ASCII case-insensitive match for a string that consists of: the literal string "text/html;", optionally followed by any number of space characters, followed by the literal string "charset=", followed by one of the labels of the character encoding of the character encoding declaration.

A document must not contain both a meta element with an http-equiv attribute in the encoding declaration state and a meta element with the charset attribute present. (emphasis mine)

因此,如果您要使用http-equiv,则必须将其用作<meta http-equiv="Content-Type" content="text/html; charset=utf-8">。但是,这只是 <meta charset="utf-8"> 的另一种说法,所以请使用缩写形式。