The class attribute helps group HTML elements so you can style or control them together easily.
0
0
Class attribute in HTML
Introduction
You want to make several buttons look the same color and size.
You want to apply the same style to multiple paragraphs.
You want to select certain elements with JavaScript to add behavior.
You want to organize your page elements for easier design changes.
You want to highlight some text blocks with a special background.
Syntax
HTML
<tag class="class-name">Content</tag>
You can add multiple classes by separating them with spaces, like
class="class1 class2".Class names should be meaningful and use letters, numbers, hyphens, or underscores.
Examples
A paragraph with a class named 'highlight' to style it specially.
HTML
<p class="highlight">This is important text.</p>
A div with two classes 'box' and 'container' to apply multiple styles.
HTML
<div class="box container">Content inside a box and container.</div>
A button with classes 'btn' and 'primary' for styling and behavior.
HTML
<button class="btn primary">Click me</button>
Sample Program
This example shows how the class attribute is used to style a paragraph and a button. The paragraph has a yellow background and some padding. The button has blue background, white text, and changes color when hovered.
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Class Attribute Example</title> <style> .highlight { background-color: #ffeb3b; padding: 0.5rem; border-radius: 0.25rem; } .btn { background-color: #2196f3; color: white; border: none; padding: 0.75rem 1.5rem; font-size: 1rem; border-radius: 0.3rem; cursor: pointer; transition: background-color 0.3s ease; } .btn:hover { background-color: #1976d2; } </style> </head> <body> <p class="highlight">This paragraph is highlighted with a yellow background.</p> <button class="btn">Click me</button> </body> </html>
OutputSuccess
Important Notes
Class names are case-sensitive, so Highlight and highlight are different.
Using classes is better than using inline styles because it keeps your HTML clean and styles reusable.
You can use the browser's developer tools (right-click element -> Inspect) to see which classes an element has and how styles apply.
Summary
The class attribute groups elements for styling or scripting.
You can assign multiple classes separated by spaces.
Use meaningful class names to keep your code clear and easy to maintain.