class
一个以空格分隔的元素的类名(classes)列表,它允许CSS和Javascript通过类选择器(classselectors)或DOM方法(document.getElementsByClassName)来选择和访问特定的元素。
浏览器支持
所有浏览器都支持class属性 |
示例
<p>Narrator: This is the beginning of the play.</p> <p class="note editorial">Above point sounds a bit obvious. Remove/rewrite?</p> <p>Narrator: I must warn you now folks that this beginning is very exciting.</p> <p class="note">[Lights go up and wind blows; Caspian enters stage right]</p> <style> .output { font: 1rem 'Fira Sans', sans-serif; } .note { font-style: italic; font-weight: bold; } .editorial { background: rgb(255, 0, 0, .25); padding: 10px; } .editorial:before { content: 'Editor: '; } </style>
Narrator: This is the beginning of the play.
Above point sounds a bit obvious. Remove/rewrite?
Narrator: I must warn you now folks that this beginning is very exciting.
[Lights go up and wind blows; Caspian enters stage right]
尽管对class 的命名没有要求,但 web 开发者最好使用可以表达元素语义目的的名称,而不是描述元素展现的名称(即使一个元素是斜体,但是 class 的命名也不应该是 italics)。语义化命名即使在页面展现发生改变时仍能合乎逻辑。
实例在 html 文档中使用 class 属性:
<html> <head> <style> h1.intro{color:blue;} p.important{color:green;} </style> </head> <body> <h1 class="intro">header 1</h1> <p>a paragraph.</p> <p class="important">note that this is an important paragraph.:)</p> </body> </html>
定义和用法
class 属性定义了元素的类名。
class 属性通常用于指向样式表的类。但是,它也可以用于 JavaScript 中(通过 HTML DOM),来修改 HTML 元素的类名。
HTML 4.01 与 HTML5之间的差异
在 HTML5 中, class 属性可用于任何的 HTML 元素(它会验证任何HTML元素。但不一定是有用)。
在 HTML 4.01 中, class 属性不能用于:<base>,<head>,<html>,<meta>,<param>,<script>,<style>,和<title>。
语法
<element class="classname">
属性值
值 | 描述 |
---|---|
classname | 规定元素的类的名称。如需为一个元素规定多个类,用空格分隔类名。<span >. HTML 元素允许使用多个类。 名称规则:
|