HTML provides ways to select and style elements using IDs and Classes. Let’s understand what they are and how they work.
What is an ID?
An ID is a unique identifier assigned to only one HTML element within a page. It’s used for unique styling and JavaScript manipulations.
Example
<div id="myUniqueID">This is a div with an ID.</div>What are Classes?
Classes allow you to give the same name to multiple HTML elements, making it easy to change their look or behavior collectively. They are not unique and can be assigned to multiple elements.
Example
<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 embed CSS (Cascading Style Sheets) within an HTML document. It defines the appearance of HTML elements, such as colors, sizes, and margins.
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>
Using IDs and Classes in CSS
In CSS, IDs are selected using a hash symbol (#) before the ID, while classes are selected using a dot (.) before the class name.
Example
/* CSS for ID */
#myUniqueID {
background-color: yellow;
}
/* CSS for Class */
.myClass {
font-size: 18px;
}Differences Between IDs and Classes
- Uniqueness: IDs are unique, while classes can be reused.
- JavaScript: IDs are often used for JavaScript operations.
- Styling: Both can be used for styling, but IDs have higher specificity.
Understanding the difference between IDs and Classes is essential for effective web development. While IDs are for unique elements, classes are for grouping elements.