What are HTML Attributes?
HTML attributes provide extra information about elements. They are always written in the start tag, and usually come as name="value" pairs.
Syntax:
<tagname attribute="value">Content</tagname>
Example 1: href Attribute in <a> Tag (Hyperlink)
Code:
<a href="https://www.wikipedia.org">Go to Wikipedia</a>
Output:
Go to Wikipedia
Explanation:
- href is the attribute
- "https://www.wikipedia.org" is the value
It tells the browser where the link should go.
Example 2: src and alt Attributes in <img> Tag
Code:
<img src="https://via.placeholder.com/100" alt="Sample Image">
Output:
<img src="https://via.placeholder.com/100" alt="Sample Image">
Explanation
- src = Source of the image
- alt = Alternative text shown if image doesn't load
Example 3: style Attribute (Inline CSS Styling)
Code:
<p style="color: blue; font-size: 18px;">This is a styled paragraph.</p>
Explanation:
- style lets you add CSS directly inside HTML
- You can change color, size, font, etc.
Example 4: title Attribute (Tooltip on Hover)
Code:
<p title="This is a tooltip">Hover over this text</p>
Output:
<p title="This is a tooltip">Hover over this text</p>
Explanation
- he title attribute shows a tooltip when you hover over the element
Example 5: type and value in <input> Tag (Form Input)
Code:
<input type="text" value="Enter your name">
Output:
<input type="text" value="Enter your name">
Explanation:
type="text"
makes it a text boxvalue="Enter your name"
pre-fills the input
Example 6: colspan in <td> Tag (Table Cell Spanning)
Code:
<table border="1">
<tr>
<td colspan="2">Merged Cell</td>
</tr>
<tr>
<td>Left</td>
<td>Right</td>
</tr>
</table>
Output:
Merged Cell | |
Left | Right |
Explanation:
-
colspan="2"
makes the cell span across two columns
Summary of Most Common HTML Attributes
Attribute | Purpose |
---|---|
href | Link to a URL |
src | Image or media source |
alt | Alternate text for images |
style | Inline CSS styling |
title | Tooltip on hover |
type | Type of input element |
value | Default value in input field |
colspan | Merge columns in tables |