The class Attribute

The class attribute is used to categorize elements. Then we can add style to those elements.

You can add multiple classes to an element by separating the class names with a space. The following code shows how you can apply the class attributes.

 
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
      <a class="class1 class2" href="http://java2s.com">Java2s.com web site</a>
      <p />
      <a class="class2 otherclass" href="http://w3c.org">W3C web site</a>
</body>
</html>
  

The following code define a style on classes:

 


<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style type="text/css">
.class2 {
      background-color: grey;
      color: white;
      padding: 5px;
      margin: 2px;
}

.class1 {
      font-size: x-large;
}
</style>
</head>
<body>
      <a class="class1 class2" href="http://java2s.com">java2s.com web site</a>
      <p />
      <a class="class2 otherclass" href="http://w3c.org">W3C web site</a>
</body>
</html>
  

We can also use the class attribute in a Javascript.

 
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
      <a class="class1 class2" href="http://java2s.com">java2s.com web site</a>
      <p />
      <a class="class2 otherclass" href="http://w3c.org">W3C web site</a>
      <script type="text/javascript">
            var elems = document.getElementsByClassName("otherclass");
            for (i = 0; i < elems.length; i++) {
                  var x = elems[i];
                  x.style.border = "thin solid black";
                  x.style.backgroundColor = "white";
                  x.style.color = "black";
            }
      </script>
</body>
</html>
  
Home 
  HTML CSS Book 
    HTML  

HTML5 Global Attributes:
  1. The accesskey Attribute
  2. The class Attribute
  3. The contenteditable Attribute
  4. The contextmenu Attribute
  5. The dir Attribute
  6. The draggable Attribute
  7. The dropzone Attribute
  8. The hidden Attribute
  9. The id Attribute
  10. The lang Attribute
  11. The spellcheck Attribute
  12. The style Attribute
  13. The tabindex Attribute
  14. The title Attribute
Related: