HTML Attributes
HTML Attributes
In HTML, attributes provide extra information about an element. They are always specified in the start tag and usually come in name/value pairs like name="value".
Understanding Attributes
An HTML attribute modifies the default functionality of an element type or provides functionality to certain elements unable to function correctly without them. For example, the <a> element needs an href attribute to specify the URL of the page the link goes to.
Here are a few key points:
- Attributes are added to the opening tag.
- They consist of a name and a value.
- The value should ideally be enclosed in double quotes.
Example
<a href="https://example.com">Visit Example</a>
In the snippet above, href is the attribute name and "https://example.com" is the attribute value.
Types of Attributes
Attributes can generally be categorized into a few types:
- Core Attributes: These can be used on almost every HTML element. Examples include
id,class,style, andtitle. - Internationalization Attributes: Used for managing language and text direction. Examples include
dirandlang. - Element-Specific Attributes: These are attributes that only apply to specific elements. For instance, the
srcattribute is used with<img>,<script>, and<audio>elements, but wouldn't make sense on a<p>element.
Common Core Attributes
The title Attribute
The title attribute adds extra information about an element. The value of the title attribute will be displayed as a tooltip when you mouse over the element.
<p title="I am a tooltip">Hover over this paragraph.</p>
The style Attribute
The style attribute allows you to add inline CSS styling directly to an HTML element.
<p style="color: red; font-size: 20px;">This text is red and large.</p>
The href and src Attributes
href(Hypertext Reference): Specifies the URL of the page the link goes to. Used primarily with<a>tags.src(Source): Specifies the path to the image, video, or script to be displayed or loaded. Used primarily with<img>,<video>,<script>, etc.
<a href="https://github.com">Link to GitHub</a>
<img src="logo.png" alt="Company Logo" />
By mastering attributes, you can make your HTML elements much more powerful, interactive, and semantic!
💡 Himubey Tip
Although you can omit quotes around attribute values in HTML5 if there are no spaces (like width=100), it is an industry best practice to ALWAYS wrap your attribute values in double quotes (width="100"). It prevents unexpected bugs.
Interview Questions
- Where are attributes always placed in an HTML element?
- What is the purpose of the
srcattribute, and which tags commonly use it? - Explain the function of the
titleattribute.