Id & Classes
HTML offers multiple ways to select and style elements. Two of the most commonly used selectors are IDs and Classes. This lesson explores what they are, how to use them, and their differences.
What is an ID?
An ID is an attribute that provides a unique identifier for an HTML element within a page. It is commonly used when an element needs to be uniquely targeted by CSS or JavaScript.
<div id="myUniqueID">This is a div with an ID.</div>
What are Classes?
The class attribute lets you give the same class name to
multiple HTML elements. This allows you to easily apply the same styling
or behavior to multiple elements.
Classes are not unique and can be assigned to multiple elements. They are generally used for applying the same styles or behaviors to a group of elements.
<div class="myClass">This is a div with a class.</div>
<p class="myClass">This is a paragraph with the same class.</p>
The Style Tag
The <style> tag in HTML is used to include embedded
CSS (Cascading Style Sheets) within an HTML document.
It is commonly placed inside the <head> section
of an HTML document. The <style> tag allows you
to define the look and feel of HTML elements, including their colors,
sizes, margins, spacing, and other visual properties.
Here's a simple example:
<!DOCTYPE html>
<html>
<head>
<style>
/* CSS rules go here */
p {
color: blue;
font-size: 18px;
}
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<p>This is a blue paragraph.</p>
<p class="highlight">
This paragraph has a yellow background.
</p>
</body>
</html>
In this example, we have targeted the second paragraph by its class name
in CSS. The <style> tag is used to add CSS directly
inside an HTML document.
We will learn more about CSS and selectors later in the CSS tutorial.
Using IDs and Classes in CSS
In CSS, elements with IDs are selected using a hash (#) symbol before the ID, while elements with classes are selected using a dot (.) before the class name.
/* CSS for ID */
#myUniqueID {
background-color: yellow;
}
/* CSS for Class */
.myClass {
font-size: 18px;
}
Differences Between IDs and Classes
- Uniqueness: IDs should be unique within a page, while classes can be reused across multiple elements.
- JavaScript: IDs are commonly used when JavaScript needs to target a specific element.
- Styling: Both IDs and classes can be used for styling, but ID selectors have higher CSS specificity than class selectors.
Conclusion
Understanding the difference between IDs and Classes is crucial for effective web development.
While IDs are intended for uniquely identifying elements, classes are designed for grouping elements that share common styling or behavior.