HTML Classes
In this page:
<tagname class="classname">content</tagname>
<style>
.classname {
property: value;
}
</style>
What is the class Attribute?
The class attribute is used to group multiple HTML elements together. By assigning a class name to various elements, you can apply identical styles or scripts to all of them simultaneously.
Example: What is the class Attribute?
<p class="highlight">First</p>
<p class="highlight">Second</p>
Selecting Classes with CSS
To target and style classes inside your stylesheet, you use a dot (.) followed by your exact class name. This selects every element on the webpage possessing that class name.
Example: Selecting Classes with CSS
<style>
.highlight {
color: orange;
}
</style>
<p class="highlight">Styled by class</p>
Using Multiple Classes Together
An HTML element is not limited to just one class. You can apply multiple class names to a single element by separating them with spaces. This allows you to combine layout and style classes dynamically.
Example: Using Multiple Classes Together
<div class="card large">Combined classes</div>
Classes in JavaScript Selectors
Classes are not just for styling. Web scripts can target elements by their class names using methods like getElementsByClassName or querySelectorAll to perform actions on multiple items at once.
Example: Classes in JavaScript Selectors
<script>
document.querySelectorAll('.highlight');
</script>
<p class="highlight">Targeted by script</p>
Semantic Class Naming Styles
Writing random or messy class names makes your code hard to read and scale. Using descriptive, semantic naming patterns (like using hyphens to separate words) makes your layout structure clear to other developers.
Example: Semantic Class Naming Styles
<div class="tool-container">Semantic, hyphenated class name</div>
- Adding a dot prefix inside your HTML class attribute values (e.g., class=".card").
- Separating multiple classes with commas instead of standard spaces.
- Naming classes with vague visual terms like blue-box which become outdated when redesigning your site.
- The class attribute groups multiple HTML elements together for group styling and scripting.
- Select and style classes inside CSS using a dot prefix followed by the exact class name.
- Apply multiple classes to a single element by separating their names with spaces inside the class attribute.
The class attribute is fully supported across all modern and legacy web browsers natively.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: