Web Development - Classes and IDs
HTML Classes and IDs
Classes and IDs allow you to give names to HTML elements. They help you style specific parts of a page with CSS or access them with JavaScript.
The class Attribute
The class attribute is used to define a group of elements with the same name.
You can style all elements with the same class using CSS.
Example
Using class in HTML:
<p class="intro">This is an introductory paragraph.</p>
<p class="intro">This is another paragraph with the same class.</p>
Try it Yourself »
You can then target this class in CSS using a dot (.):
Multiple Classes
You can assign multiple classes to the same element by separating them with spaces.
Example
Using multiple classes:
<p class="intro highlight">This paragraph has two classes.</p>
Try it Yourself »
This allows flexible styling by combining different class rules.
The id Attribute
The id attribute is used to uniquely identify a single element.
Each id must be unique within a page.
In CSS, IDs are targeted using a hash symbol (#):
Difference Between Class and ID
A class can be used on multiple elements.
An id is used on one element only.
Example
Comparing class and id:
<p class="highlight">This uses a class.</p>
<p id="unique">This uses an ID.</p>
Example CSS
.highlight { color: green; }
#unique { color: orange; }
Try it Yourself »
Using Classes and IDs in the Same Page
You can use both class and id in the same page to style different parts or to interact with JavaScript.
Example
Combining class and id:
<div id="main-content" class="content-box">
<h2>Welcome!</h2>
<p>This is the main content section.</p>
</div>
Try it Yourself »
Using IDs for Bookmarks
The id attribute can also be used as a link target (bookmark) within the same page.
Example
Using id for bookmarks:
<a href="#section2">Go to Section 2</a>
<h2 id="section2">Section 2</h2>
<p>Welcome to section 2!</p>
Try it Yourself »
JavaScript and IDs
IDs are also useful when working with JavaScript.
You can use document.getElementById() to access an element by its ID.
Example
Using an ID with JavaScript:
<p id="demo">Hello World!</p>
<button onclick="changeText()">Click me</button>
<script>
function changeText() {
document.getElementById("demo").innerHTML = "You clicked the button!";
}
</script>
Try it Yourself »
Best Practices
- Use
classfor reusable styles. - Use
idfor unique elements. - Do not use the same
idon more than one element. - Use meaningful names (e.g.,
header,main-content).
Next, you'll learn about HTML Forms - how to collect user input with text fields, buttons, and checkboxes.