Classes and Ids
HTML Classes & IDs
Classes and IDs are crucial attributes in HTML that help in styling and uniquely identifying elements with CSS and JavaScript. While both are used for element selection, they serve different functions and should be used accordingly.
HTML Classes
Purpose
Classes allow grouping multiple elements together, enabling shared styles and behavior across them.
Syntax
The class
attribute can be assigned to any HTML element.
<tag class="classname"></tag>
Usage
Classes can be applied to multiple elements to maintain consistency in styling.
London is the capital of England.
Paris is the capital of France.
Tokyo is the capital of Japan.
<!DOCTYPE html>
<html>
<body>
<style>
.myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
.city {
background-color: tomato;
color: white;
padding: 10px;
}
</style>
<h1 class="myHeader">My Cities</h1>
<h2 class="city">London</h2>
<p>London is the capital of England.</p>
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</body>
</html>
Styling Elements with Classes
Using CSS, elements with the same class name can be uniformly styled.
This is some important text.
<h1>My <span class="note">Important</span> Heading</h1>
<p>This is some <span class="note">important</span> text.</p>
.note {
font-size: 120%;
color: red;
}
Conclusion - Classes
The class
attribute assigns one or more class names to an element.Used by CSS
and JavaScript
for styling and interaction.Multiple elements can share the same class.JavaScript
can access elements with a class using getElementsByClassName()
.
HTML IDs
Purpose
IDs uniquely identify a single element within a page.
Syntax
The id
attribute can be assigned to any HTML element.
<tag id="uniqueID"></tag>
Example
Below, the <p>
element is assigned a unique ID, and its text color is modified using inline CSS.
This text is styled using the ID attribute.
<p id="my-paragraph" style="color: aqua;">
This text is styled using the ID attribute.
</p>
Conclusion
class
allow for grouping multiple elements and applying shared styles, making them useful for consistent styling across a page. id
, on the other hand, are unique and target a single element, ensuring precise identification. class
are reusable, while id
must remain unique within the document.
Emojis
Emojis, part of the UTF-8 character set, are used in HTML to incorporate expressive symbols and icons. They can be inserted using Unicode codes or emoji entities, such as 😀 for 😀, adding visual elements to text.
Block & Inline elements
Block elements such as <div> and <p> occupy the full width of their container and begin on a new line, whereas inline elements like <span> flow seamlessly within text.