HTML Classes
The class
attribute is used to assign one or more class names to an element. Classes serve as hooks for styling with CSS or interaction with JavaScript. By using classes, you can apply consistent styles to multiple elements without repeating inline styles.
Key Topics
Basic Class Usage
Example: Assigning a class to an element for styling.
<p class="highlight">This paragraph is highlighted.</p>
Multiple Classes
Example: An element can have multiple classes separated by spaces.
<div class="container main-section">Content</div>
Class Example
This example shows how classes can be used to style multiple elements in a consistent way. A full code sample is provided below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" >
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<title>Classes Example</title>
<style>
.highlight {
background:yellow;
font-weight:bold;
}
.note {
color:gray;
font-style:italic;
}
</style>
</head>
<body>
<p class="highlight">This text is highlighted.</p>
<p class="highlight note">This text is highlighted and noted.</p>
</body>
</html>
Explanation: The classes highlight
and note
apply different styles. By combining them, the second paragraph inherits both sets of styles, demonstrating flexible and reusable styling.
Key Takeaways
- The
class
attribute lets you apply CSS rules to multiple elements simultaneously. - Use descriptive class names for easier maintenance and readability.
- Multiple classes per element allow for modular and reusable styling.
- Classes work well with CSS and JavaScript for dynamic interactions.
- Keep class naming consistent to maintain a clean codebase.