描述 (Description)
While the name of an element specifies its type, the class
attribute lets you assign to it one or more subtypes. These subtypes may then be used in CSS code for styling purposes, or by JavaScript code (via the Document Object Model, or DOM) to make changes, or add behavior, to elements belonging to a particular subtype.
元素名称指定其类型时,可以使用class
属性为它分配一个或多个子类型。 然后,可以在CSS代码中将这些子类型用于样式目的,或者通过JavaScript代码(通过文档对象模型或DOM)将这些子类型用于对属于特定子类型的元素进行更改或添加行为。
Note that the class
attribute cannot be applied to the following elements:
请注意, class
属性不能应用于以下元素:
- base 基础
- basefont 基本字体
- head 头
- html html
- meta 元
- param 参数
- script 脚本
- style 样式
- title 标题
值 (Value)
This attribute takes as its value a space-delimited list of one or more class names. Unlike the id attribute, the class attribute’s value may begin with a number and will still be valid HTML; for example, <div class="3-col-wide"> … </div>
. However, it’s best avoided as the CSS 2.1 specification says that CSS identifiers, which would include the class name that matches the class
attribute in the HTML, should not begin with a digit. By not starting class names with a digit, you’ll be keeping both HTML and CSS validators happy.
此属性将一个或多个类名称的以空格分隔的列表作为其值。 与id属性不同,class属性的值可以以数字开头,并且仍然是有效HTML; 例如<div class="3-col-wide"> … </div>
。 但是,最好避免使用CSS 2.1规范,因为CSS标识符(包括与HTML中的class
属性匹配的class
名) 不应以digit开头 。 通过不使用数字开头的类名,您将使HTML和CSS验证程序都满意。
While there have been numerous calls from the developer community to specify a standard set of class names and associated meanings, at the moment you’re free to specify whatever class names make sense to you. As with all HTML markup, however, it’s recommended that you use names that are as semantically meaningful as possible; the class name should indicate to a human who reads it what that element’s purpose or meaning is, rather than how it looks. Hence, purely presentational class names like “large
” or “shiny
” are bad practice, while class
names such as “executive-summary
” or “key-findings
” provide some useful information to those reading the markup.
尽管开发人员社区发出了无数电话来指定一组标准的类名和相关含义,但现在您可以自由指定对您有意义的任何类名。 但是,与所有HTML标记一样,建议您使用在语义上尽可能有意义的名称。 类名应该向阅读它的人指示该元素的目的或含义是什么,而不是其外观。 因此,纯表述性的类名(例如“ large
”或“ shiny
”)是不好的做法,而class
名(如“ executive-summary
”或“ key-findings
”)为阅读标记的人员提供了一些有用的信息。
While it’s good to make the markup human-readable, the developer community has made great strides in standardizing the usage of class names for certain types of information on the Web, such as contact details or calendar events, so that the markup can also be read, or parsed, by web-based services to great effect. The result of this standardization effort is known as Microformats.
虽然使标记易于阅读是件好事,但开发人员社区在标准化类名称对Web上某些特定类型信息(例如联系方式或日历事件)的使用方面取得了长足的进步,以便可以读取标记,或通过基于Web的服务进行分析可以产生很大的效果。 这种标准化工作的结果被称为微格式 。