HTML Attributes

What are Attributes?
Attributes provide extra information about HTML elements. They are always included in the opening tag and usually come in a name="value" format. Attributes help define the behavior, appearance, and purpose of elements.

Examples of Common Attributes

  • <a href="https://example.com">Visit Example</a>
    → The href attribute defines the link destination.
  • <img src="image.jpg" alt="A sample image">
    src sets the image path, alt provides alternative text.
  • <input type="text" placeholder="Enter your name">
    type defines input type, placeholder shows a hint.
  • <p title="This is a tooltip">Hover me</p>
    title shows extra info when hovered.
  • <button disabled>Click Me</button>
    disabled makes the button unclickable.

Structure of an Attribute

<element attribute="value">Content</element>

Example:
<a href="about.html">About Us</a>
<img src="logo.png" alt="Company Logo">

Types of Attributes

1. Required Attributes
Some elements won’t work properly without specific attributes. Example: <img> requires src.

2. Optional Attributes
Attributes that improve functionality but are not required. Example: alt in <img>.

3. Global Attributes
Can be applied to almost all HTML elements. Examples: id, class, title, style.

Global Attribute Examples

<p id="intro" class="highlight" style="color:blue;" title="Intro Text"> Welcome to CodeWithHamza! </p>

Boolean Attributes

Some attributes don’t need a value. They work just by being present. Example:

<input type="checkbox" checked> I agree
<button disabled>Can't Click</button>

Key Points to Remember

  • Attributes are always placed in the opening tag.
  • Most follow the name="value" format.
  • Attribute values should be in quotes (single or double).
  • Global attributes like id and class help in styling and scripting.
  • Boolean attributes (like disabled, checked, readonly) don’t need values.
  • Always provide alt text for images for better accessibility and SEO.

Practice Exercise

👉 Create a file named attributes.html. Add:

  • A link with href and title.
  • An image with src and alt.
  • A button with disabled.
  • A paragraph with class, id, and style.

Open it in your browser and test how each attribute changes the behavior of the elements.

Pro Tip 💡

Use Emmet in VS Code for quick attributes. For example: Typing img[src alt] + Enter will auto-generate <img src="" alt="">.