- Home
- /
- HTML Id & Classes
HTML Tutorial
INTRODUCTION
HTML BASIC TAGS
INLINE & BLOCK ELEMENTS
HTML LISTS
HTML TABLES
HTML FORMS
HEAD ELEMENTS
HTML MEDIA
MISCELLANEOUS TAGS
- Home
- /
- HTML Id & Classes
HTML ID & Classes
When working with HTML, it’s important to know how to target elements to style them or interact with them using JavaScript. Two of the most powerful and commonly used tools for this purpose are IDs and Classes.
What is an ID?
An ID is a special attribute you assign to a single HTML element, making it uniquely identifiable on a webpage. Think of it like giving one person in a room a special name – only they respond to it.
- IDs must be unique within a page.
- Commonly used for specific styling or JavaScript operations.
- Great for targeting one section or element, like a form, header, or button.
This is a div with an ID.
In this case, only that specific <div>
can be styled or accessed using the ID myUniqueID
.
What is a Class?
A Class is also an attribute, but unlike and ID, it is not unique. Multiple HTML elements can share the same class name. Classes are extremely useful when you want to apply the same style or behavior to several elements at one.
- Classes can be reused on any number of elements.
- Perfect for applying consistent styles like buttons, boxes, alerts, etc.
- Commonly used in both CSS and JavaScript for group behavior.
This is a div with a class.
This is a paragraph with the same class.
Both the <div>
and the <p>
now share the myClass
class, meaning they can look or behave the same when styled.
What is the <style>
Tag?
The <style>
tag in HTML allows you to write CSS directly inside your HTML document. This tag is most often placed inside the <head>
of the page and is used to define styles for elements on the page.
This is a blue paragraph.
This paragraph has a yellow background.
In this example: All <p>
elements will appear with blue text and a font size of 18px. The second paragraph, which has the class highlight
, gets a yellow background.

Using IDs and Classes in CSS
To style elements using CSS:
- Use
#
before an ID name. - Use
.
before a class name.
CSS with ID:
#myUniqueID {
background-color: yellow;
}
CSS with Class:
.myClass {
font-size: 18px;
}
Difference Between ID and Class
- ID is unique, meant for one element only.
- Class is reusable, and can be used on multiple elements.
- IDs are more specific in CSS, meaning they will override class styles if both are applied.
- IDs are often used in JavaScript to get or modify a specific element quickly.
Summary
- Use ID when you need to target a single, unique element.
- Use Class when you want to group multiple elements under one style or behavior.
- Both ID and Class help you organize and style your HTML more efficiently.
- Styling can be added using the
<style>
tag or external CSS files.