HTML Classes

❮ Previous Home Next ❯

HTML class Attribute

The HTML class attribute is used to specify a class or classes for an HTML element.

Possiblity




Syntax

Step 1: To create a class use a period (.) character, followed by a class name.

Step 2: Then, define the CSS properties within curly braces {}

.className {
  property: value;
}

Step 3: Use the class attribute to set class(es) for the element(s).

<tagName class="className(s)">



How to Use the class Attribute

The class attribute is often used to a class name in a style sheet. It can also be used by a JavaScript to access and manipulate elements with the specific class name.

This example shows how to set class for 2 <div> elements:

Example

<!DOCTYPE html>
<html>
<head>
<style>
.demo {
  background-color: tomato;
  color: white;
  border: 1px solid black;
  border-radius: 4px;
  margin: 8px;
  padding: 8px;
}
</style>
</head>
<body>

<div class="demo">
  <h2>Div 1</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>

<div class="demo">
  <h2>Div 2</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>

</body>
</html>



Single Class

Single class can be used for the element(s).

See the above example shows how to set single class for the element(s).







Multiple Classes

The HTML elements can have more than one class.

To define multiple classes, separate the class names with a space, e.g. <div class="className className">.

This example shows how to set multiple classes for the element:

Example

<div class="demo demo2">
  <h2>Div 1</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>

<div class="demo">
  <h2>Div 2</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>



How to Use different Elements for Class

The different HTML elements can allocate the same class name.

This example shows how to set single class for multiple elements:

Example

<h1 class="demo">Heading of the Page</h1>
<p class="demo">Paragraph of the page.</p>



How to Use the class Attribute in JavaScript

The class name can also be used by JavaScript to perform certain tasks for specific or all the class allotted elements.

This example shows how to use JavaScript for access elements with a specific class name with the getElementsByClassName() method:

Example

<script>
function myFunction() {
  let x = document.getElementsByClassName("demo")[0];
  x.style.display = "none";
}
</script>

You will learn more about JavaScript in our HTML JavaScript chapter.

❮ Previous Home Next ❯