The class attribute is often used to point 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.
For example, imagine you have some paragraphs on your webpage, and you want some of them to have a different background color. You can create a class, let's say "highlight," and apply it to those specific paragraphs. Then, in your style settings, you can define that anything with the "highlight" class should have a yellow background.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Classes Example</title>
<style>
/* Define styles for the "highlight" class */
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<!-- Apply the "highlight" class to a paragraph -->
<p class="highlight">This paragraph has a yellow background.</p>
<!-- Another paragraph without the "highlight" class -->
<p>This paragraph is unaffected.</p>
</body>
</html>
You can apply multiple classes to a single HTML element by separating them with spaces in the class attribute. This allows you to combine styles and behaviors from different classes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiple Classes Example</title>
<style>
/* Define styles for the classes */
.highlight {
background-color: yellow;
}
.italic {
font-style: italic;
}
.underline {
text-decoration: underline;
}
</style>
</head>
<body>
<!-- Apply multiple classes to a paragraph -->
<p class="highlight italic">This paragraph has a yellow background and is italicized.</p>
<!-- Apply a different set of classes to another paragraph -->
<p class="italic underline">This paragraph is italicized and underlined.</p>
</body>
</html>
In this example, there are three classes defined: .highlight, .italic, and .underline. You can see that you can apply multiple classes to a single paragraph element. The first paragraph has both the "highlight" and "italic" classes, while the second paragraph has "italic" and "underline" classes.