HTML class Global Attribute
Description
The class
HTML global attribute specifies one or more class names for an element. Class names are used to select and style elements in CSS, and can also be used by JavaScript to manipulate elements.
The class
attribute can be used on any HTML element, and can be specified multiple times on the same element to add multiple classes. For example, the following code would add the my-class
and my-other-class
classes to the <div>
element:
<div class="my-class my-other-class">This is my div element.</div>
Classes can be used to style elements in CSS by using class selectors. For example, the following CSS code would style all elements with the my-class
class to have a red border:
.my-class {
border: 1px solid red;
}
Classes can also be used by JavaScript to manipulate elements. For example, the following JavaScript code would get all elements with the my-class
class and set their background color to green:
const elements = document.getElementsByClassName('my-class');
for (const element of elements) {
element.style.backgroundColor = 'green';
}
The class
attribute is a powerful tool for styling and manipulating elements in HTML and CSS. It is also one of the most commonly used global attributes in HTML.
Here are some examples of how the class
attribute can be used:
- To style a group of elements the same way, such as all paragraphs on a page.
- To add additional styling to an element, such as a hover effect or a special border.
- To create responsive designs, such as hiding elements on small screens.
- To use JavaScript to interact with elements on the page, such as changing their color or position.
Overall, the class
attribute is a very versatile and useful tool for web developers.
Syntax
.classname { ... }
Values
- classnameA name used to assign to the class. Use only letters of the alphabet (AZ, az), numbers, hyphens, underscores.
Example
<!DOCTYPE html>
<html>
<head>
<title>Global class attribute</title>
<style>
.main {
text-align:center;
color:red;
}
.index {
color:blue;
}
</style>
</head>
<body>
<h1 class="main">The first level heading.</h1>
<p class="index">A paragraph with an assigned class.</p>
<p>A paragraph without an assigned class.</p>
</body>
</html>
Browser Support
The following table will show you the current browser support for the HTML class
Global Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 14th October 2023