HTML attributes are like characteristics that define an HTML element. They are put inside the element’s opening tag and have two parts the name and the value.
Name: This tells us what property the element has.
Value: This sets the value of that property.
Types of HTML Attributes
There are three main types
- Core Attributes: These are basic attributes that work with most HTML elements. Examples are id, class, and style.
- Internationalization Attributes: These help adjust the document for different languages and regions. Examples are lang and dir.
- Generic Attributes: These give extra information about the element but don’t affect how it looks or behaves. Examples are data-* attributes, used to store custom data for the page or app.
Core Attributes
There are four main types:
ID Attribute
It gives a unique identifier to an HTML element. Each element with an ID has its own unique identity.
Example
<p id="html">This is an HTML tutorial</p>
<p id="css">We learn CSS after finish HTML tutorials</p>In this example, the ID attribute helps tell apart two paragraphs by giving them different IDs: “html” and “css”.
The ID attribute is used to assign a unique identifier to each element. Each element with its own unique ID can be easily targeted and styled using CSS or manipulated using JavaScript.
Class Attribute
It links an HTML element to a specific class, usually for styling(CSS) or JavaScript.
For Example
<!DOCTYPE html>
<html>
<head>
<title>Class Attribute Example</title>
<style>
.red-text {
color: red;
}
.bold-text {
font-weight: bold;
}
</style>
</head>
<body>
<h1 class="red-text">This text is red</h1>
<p class="bold-text">This text is bold</p>
<p class="red-text bold-text">This text is both red and bold</p>
</body>
</html>Title Attribute
It provides extra information about an element and shows up as a tooltip when you hover your mouse over it.
The title attribute provides additional information about each element
Example
<h4 title="hello, reader">Title attribute</h4>Style Attribute
It lets you add inline styles to HTML elements. You can use it with CSS properties to style individual elements directly in the HTML code.
Case Sensitivity
HTML is flexible about attribute names’ case, letting you use uppercase or lowercase, like “title” or “TITLE.” But for better practices and compatibility with stricter document types like XHTML, it’s recommended to use lowercase attributes.