Loading...
HTML Classes

HTML Classes

In this tutorial, we will learn about Classes in HTML with the help of examples.


Classes

The class is an attribute that specifies the class name (one or more) for an HTML element.
The class attribute can be used on any HTML element. Different HTML elements can share the same class name.
The class attribute is used to specify a class for an HTML element. The class name can be used by CSS and JavaScript to perform some tasks for the HTML element.


Using class Attribute

A class name can be defined within the <style> element, or in the external CSS file.
The class name is case sensitive.
To create a class, write a period # character followed by a class name.

Syntax :

.className

Example :

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Class</title>
    <style>
      .cricket {
        color : blue;
      }
      .football {
        color : green;
      }
    </style>
  </head>
  <body>
    <p class = "cricket">This is a paragraph with cricket class.</p>
    <p class = "football">This is a paragraph with football class.</p>
  </body>
</html>

Output

This is a paragraph with cricket class.

This is a paragraph with football class.


Using same class in different elements

We can use same class name in different elements in an HTML file.

Example :

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Class</title>
    <style>
      .city {
        color : blue;
      }
    </style>
  </head>
  <body>
    <p class = "city">Paris is the capital of France.</p>
    <p class = "city">New Delhi is the capital of India.</p>
  </body>
</html>

Output

Paris is the capital of France.

New Delhi is the capital of India.


Using Multiple Classes

We can use one or more classes in an HTML element. These class names must be separated by a space.

Example :

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Class</title>
    <style>
      .city {
        color : red;
      }
      .home {
        background-color : black;
      }
    </style>
  </head>
  <body>
    <p class = "city">Paris is the capital of France.</p>
    <p class = "city home">New Delhi is the capital of India.</p>
  </body>
</html>

Output

Paris is the capital of France.

New Delhi is the capital of India.


Next Tutorial

We hope that this tutorial helped you develop better understanding of the concept of Class Attribute in HTML.

Keep Learning : )

In the next tutorial, you'll learn about HTML Id Attribute.

- Related Topics