HTML class 属性
HTML 全局属性 class 规定元素的类名(classname)。class 属性大多数时候用于指向样式表中的类(class)。不过,也可以利用它通过 JavaScript 来改变带有指定 class 的 HTML 元素。
实例
在 HTML 文档中使用 class 属性:
<html><head><style type="text/css">h1.intro {color:blue;}p.important {color:red;}</style></head><body><h1 class="intro">标题1</h1><p>这是一个段落。</p><p class="important">请注意这个重要的段落。:)</p></body></html>
定义和用法
class 属性规定元素的类名(classname)。class 属性大多数时候用于指向样式表中的类(class)。不过,也可以利用它通过 JavaScript 来改变带有指定 class 的 HTML 元素。
提示和注释
注释:class 属性不能在以下 HTML 元素中使用:base, head, html, meta, param, script, style 以及 title。
提示:可以给 HTML 元素赋予多个 class,例如:<span class="left_menu important">。这么做可以让一个 HTML 元素拥有多个CSS样式类。
提示:类名不能以数字开头!只有 Internet Explorer 支持这种命名方式。
浏览器支持
W3C: "W3C" 列指示 W3C 的 HTML/XHTML 推荐标准中是否定义了该属性。
| 属性 | |||||
|---|---|---|---|---|---|
| class | Yes | Yes | Yes | Yes | Yes |
语法
<element class="value">
属性值
| 值 | 描述 |
|---|---|
| classname | 规定元素的类的名称。如需为一个元素规定多个类,用空格分隔类名。 |
更多实例
一个html拥有多个CSS样式类
<!DOCTYPE html><html><head><style>h1.intro {color: blue;text-align: center;}.important {background-color: yellow;}</style></head><body><h1 class="intro important">标题1</h1><p>这是一个段落。</p></body></html>
<!DOCTYPE html><html><body><div class="example">第1个div元素 用 class="example" 样式。</div><div class="example">第2个div元素 用 class="example" 样式。</div><p>单击按钮将黄色背景色添加到class=“example”(索引0)的第一个div元素。</p><button onclick="myFunction()">点击一下</button><script>function myFunction() {var x = document.getElementsByClassName("example");x[0].style.backgroundColor = "yellow";}</script></body></html>
<!DOCTYPE html><html><head><style>.mystyle {margin: 20px;width: 300px;height: 50px;background-color: coral;color: white;font-size: 25px;}</style></head><body><p>点击按钮把 mystyle 样式添加到div元素</p><button onclick="myFunction()">Try it</button><div id="myDIV">我有一个div元素</div><br><script>function myFunction() {document.getElementById("myDIV").classList.add("mystyle");}</script></body></html>