HTML Attributes

HTML attributes provide additional information about HTML elements. They can control behavior, appearance, or functionality of elements and are always written inside the opening tag.

Advertisement

What is an HTML Attribute?

Attributes are usually written in name="value" format and placed inside the element's opening tag.

<a href="https://www.google.com/">Visit Google</a>

Here, href is the attribute name, and "https://www.google.com/" is its value.

Basic Structure

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

Common HTML Attributes

1. href (Hyperlinks)

<a href="https://example.com">Visit Example</a>

2. src (Images)

<img src="image.jpg" alt="Sample Image">

3. alt (Alternative Text)

Describes images for accessibility or when the image fails to load.

4. title (Tooltip)

<p title="This is a tooltip">Hover over this text</p>

5. id and class

<div id="header">Site Header</div>
<p class="highlight">Important paragraph</p>

HTML
▶ Run it
<!DOCTYPE html>
<html>
<head>
  <title>HTML Attributes</title>
</head>
<body>

  <a href="https://www.google.com/">Visit Google</a>
  <p title="This is a tooltip">Hover over this text</p>
  

 

</body>
</html>

Global Attributes

Attributes that can be applied to any element:

  • id – unique identifier
  • class – group elements
  • style – inline CSS styles
  • title – tooltip text
  • hidden – hide element

Form Attributes

Forms have specific attributes that control input behavior:

<input type="text" name="username" placeholder="Enter your name">
<input type="email" required>
  • type – input type (text, email, password)
  • name – identifies the input
  • placeholder – hint text inside input
  • required – must be filled

Event Attributes

Event attributes allow elements to respond to user actions:

<button onclick="alert('Hello!')">Click Me</button>

onclick triggers a JavaScript action when the button is clicked.

Common Mistakes

  • Forgetting quotes around attribute values.
  • Using invalid attribute names.
  • Misplacing attributes outside the opening tag.
  • Confusing global vs element-specific attributes.

Best Practices

  • Use descriptive names for id and class.
  • Always include alt text for images.
  • Keep HTML attributes lowercase and consistent.
  • Use semantic and meaningful attributes for accessibility.
Tip: Mastering HTML attributes allows you to control and enhance every element on your webpage.