In HTML, classes are used to define a group of elements that share the same styles and behaviors. They are one of the most important features in HTML for styling and JavaScript manipulation.
You create a class using the class
attribute within an HTML tag and then define the styles for that class in a CSS file or within a <style>
tag.
Creating and Using Classes in HTML
Define a Class in CSS:
You define a class in CSS by prefixing the class name with a dot (
.
)..example-class { color: blue; font-size: 20px; margin: 10px; }
Apply the Class to HTML Elements:
You can apply the class to any HTML element by using the
class
attribute.<div class="example-class">This is a div with a class.</div> <p class="example-class">This is a paragraph with the same class.</p>
Complete example with both the HTML and CSS
<!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> .example-class { color: blue; font-size: 20px; margin: 10px; } .another-class { background-color: yellow; padding: 15px; } </style> </head> <body> <div class="example-class">This is a div with a class.</div> <p class="example-class another-class">This is a paragraph with multiple classes.</p> <span class="example-class">This is a span with a class.</span> </body> </html>
CSS Class Definition:
.example-class
is defined in the CSS with styles for text color, font size, and margin..another-class
is defined with styles for background color and padding.
HTML Elements with Classes:
- The
<div>
,<p>
, and<span>
elements are all using theexample-class
class. - The
<p>
element is also using an additional classanother-class
, demonstrating how multiple classes can be applied to the same element.
- The
Tips
- Multiple Classes: You can add multiple classes to an element by separating them with a space.
- Reusability: Classes allow you to reuse the same styles across multiple elements, making your CSS more efficient and your HTML more consistent.
- JavaScript: You can also use classes to manipulate elements in JavaScript, adding, removing, or toggling classes based on user interactions or other events.