Skip to main content

Attributes

Introduction: Supercharging Your HTML 🔌

You know how to create HTML tags, but how do you customize them? Attributes are your answer!

Think of attributes like settings or controls that modify how HTML elements behave.

Real-World Analogy: Customizing Your Car 🚗

Basic Car (HTML Tag):
<car>

Customized Car (HTML Tag with Attributes):
<car color="red" speed="fast" doors="4">
↑ ↑ ↑ ↑
Attribute Value Attribute Value

Just like car options customize your vehicle, attributes customize HTML elements!

What are Attributes? ⚙️

Attributes provide extra information about HTML elements.

Attribute Anatomy

<tagname attribute="value">Content</tagname>
↑ ↑
Name Value

Structure:

  • Name - What you're setting (like id, class, src)
  • Value - The setting (in quotes: "value")
  • Location - Always in the opening tag

Basic Example

<h1 id="main-title" class="header">Welcome!</h1>
↑ ↑
Attribute 1 Attribute 2

Breaking it down:

  • id="main-title" - Gives unique identifier
  • class="header" - Assigns CSS class for styling

Visual Output:

Welcome!

(Behind the scenes, this heading can now be styled and referenced!)

Attribute Syntax Rules 📏

1. Always in opening tag

<img src="photo.jpg">
<img>src="photo.jpg"</img>

2. Name then equals then value

<a href="url">
<a "url"=href>

3. Use quotes around values

<img alt="A cat"> ✅ (double quotes)
<img alt='A cat'> ✅ (single quotes)
<img alt=A cat> ❌ (no quotes - breaks with spaces!)

4. Multiple attributes separated by spaces

<img src="photo.jpg" alt="Sunset" width="500">
Case Sensitivity

Attributes are case-insensitive (but lowercase is standard):

<!-- All work the same -->
<h1 id="heading">Text</h1> ✅ Recommended
<h1 ID="heading">Text</h1> ✅ Works
<h1 Id="heading">Text</h1> ✅ Works

<!-- But stick to lowercase! -->

Best practice: Always use lowercase for consistency! 🔡

Quick Reference: Most Used Attributes

AttributePurposeExample
idUnique identifier<div id="header">
classCSS styling group<p class="intro">
srcImage/script source<img src="cat.jpg">
hrefLink destination<a href="page.html">
altImage description<img alt="A cat">
styleInline CSS<p style="color:red">
titleTooltip text<span title="Info">

Attribute Categories 📚

Attributes are organized into categories based on their purpose:

┌──────────────────────────────────────┐
│ Global Attributes │
│ → Work on ANY element │
│ → id, class, style, title... │
└──────────────────────────────────────┘

┌──────────────────────────────────────┐
│ Specific Attributes │
│ → Only for certain elements │
│ ├─ Event (onclick, onload...) │
│ ├─ Form (action, method...) │
│ ├─ Link (href, target...) │
│ ├─ Image (src, alt...) │
│ └─ Table (legacy, now CSS...) │
└──────────────────────────────────────┘

Learning path:

  1. Start with Global - Work everywhere, learn first!
  2. Then Specific - Learn as you encounter each element type

Let's explore each category! 👇

Global Attributes 🌍

Global attributes work on ANY HTML element! Master these first.

id - Unique Identifier 🆔

Think of it like a Social Security Number - each element gets one unique ID.

<h1 id="main-title">Welcome</h1>
<p id="intro-text">This is paragraph 1</p>
<p id="description">This is paragraph 2</p>

Why use id?

1. JavaScript targeting:

// Find element by ID
document.getElementById("main-title").style.color = "blue";

2. CSS styling (specific element):

#main-title {
color: blue;
font-size: 32px;
}

3. Anchor links (jump to section):

<a href="#contact">Jump to Contact</a>
<!-- Somewhere below... -->
<section id="contact">Contact Us!</section>
IMPORTANT: IDs Must Be Unique!
<!-- ❌ WRONG - Same ID used twice -->
<div id="box">Box 1</div>
<div id="box">Box 2</div>

<!-- ✅ CORRECT - Each ID is unique -->
<div id="box1">Box 1</div>
<div id="box2">Box 2</div>

Rule: Only ONE element per page can have a specific ID!

class - Group Styling 🎨

Think of classes like uniforms - many elements can wear the same class!

Unlike id, classes can be reused!

<style>
.highlight {
background-color: yellow;
}
</style>

<p class="highlight">This is highlighted</p>
<span class="highlight">This is also highlighted</span>
<div class="highlight">This too!</div>

Output:

This is highlighted

This is also highlighted
This too!

Comparison: id vs class

Featureidclass
UniquenessOnly 1 per pageReusable
CSS selector#my-id.my-class
Use caseUnique elementsGroups of elements
Example<div id="header"><p class="text">

Visual:

ID (unique):
header ← Only one!

Class (reusable):
article ← Can have many!
article
article

Multiple Classes - Combine classes with spaces!

<style>
.blue-text {
color: blue;
}

.large-text {
font-size: 24px;
}

.bold-text {
font-weight: bold;
}
</style>

<p class="blue-text large-text bold-text">
This text is blue, large, AND bold!
</p>

Output:

This text is blue, large, AND bold!

How it works:

<element class="class1 class2 class3">
↑ ↑ ↑
Space-separated list

style - Inline CSS 🎨

Add CSS directly to an element (not recommended for large projects).

<p style="color: red; font-size: 20px;">Red text, 20px size</p>

Output:

Red text, 20px size

Best practice:

<!-- ❌ Not ideal (inline styles) -->
<p style="color: blue;">Text</p>

<!-- ✅ Better (use classes) -->
<style>
.blue-text { color: blue; }
</style>
<p class="blue-text">Text</p>
When to use style

Use inline styles for:

  • Quick testing/prototyping
  • Dynamic styles from JavaScript

Use classes for:

  • Production code
  • Reusable styles
  • Better organization

title - Tooltip Text 💬

Shows text when hovering over an element.

<abbr title="HyperText Markup Language">HTML</abbr>
<button title="Click to submit form">Submit</button>
<img src="photo.jpg" alt="Cat" title="This is my cat Fluffy">

Try it - Hover over the image:

Rizwan Ashiq

Use cases:

  • Abbreviations/acronyms
  • Extra information
  • Help text for buttons/icons

contenteditable - Make Text Editable ✏️

Allows users to edit content directly in the browser!

<p contenteditable="true">Click to edit this text!</p>

Try it - Click and edit:

Click to edit this text!

Use cases:

  • Rich text editors
  • Note-taking apps
  • Inline editing features

hidden - Hide Elements 👻

Completely hides an element from view.

<p>This is visible</p>
<p hidden>This is hidden</p>
<p>This is also visible</p>

Output:

This is visible

This is also visible

Difference from CSS:

<!-- hidden attribute -->
<div hidden>Completely removed from layout</div>

<!-- CSS display: none -->
<div style="display: none;">Same effect as hidden</div>

<!-- CSS visibility: hidden -->
<div style="visibility: hidden;">Hidden but takes up space</div>

Other Global Attributes

AttributePurposeExample
accesskeyKeyboard shortcut<button accesskey="s">Save</button>
tabindexTab order<input tabindex="1">
langLanguage<p lang="es">Hola</p>
dirText direction<p dir="rtl">Right to left</p>
Global Attributes Recap

Most important to learn first:

  1. id - Unique identifier
  2. class - Reusable styling
  3. style - Inline CSS
  4. title - Tooltips

Master these 4, then explore the rest!

Event Attributes

Event attributes are used to define JavaScript code that will run when a specific event occurs on an HTML element. These attributes are added to an HTML element to make it interactive and responsive to user actions.

Here are some of the most commonly used event attributes in HTML along with coding examples:

onclick

This attribute is used to run JavaScript code when an element is clicked.

<button onclick="alert('Hello, world!')">Click me!</button>

This will give the following result:

onmouseover

Used to run JavaScript code when the mouse is moved over an element.

<img src="image.jpg" onmouseover="alert('You hovered over the image!')" />

If you open this in a browser and move your mouse over the image, an alert box pops up. (The example is not rendered live here because an alert firing on every hover gets annoying fast.)

onload

This attribute is used to run JavaScript code when a web page or image has finished loading.

<body onload="alert('The page has finished loading!')"></body>

onsubmit

This attribute is used to run JavaScript code when a form is submitted.

<form onsubmit="alert('The form has been submitted!')">
<!-- Form fields go here -->
<button type="submit">Submit</button>
</form>

This will give the following result:

onkeydown

This attribute is used to run JavaScript code when a key on the keyboard is pressed down.

<input type="text" onkeydown="alert('You pressed a key!')" />

onfocus

This attribute is used to run JavaScript code when an element receives focus, such as when a user clicks on it or tabs to it.

<input type="text" onfocus="alert('This input field has received focus!')" />

onblur

This attribute is used to run JavaScript code when an element loses focus, such as when a user clicks away from it or tabs to another element.

<input type="text" onblur="alert('This input field has lost focus!')" />

These are just a few examples of the many event attributes available in HTML. Using event attributes correctly can make your web pages more interactive and engaging for users.

Form Attributes

Form attributes are used to define the behavior of form elements, such as input fields, checkboxes, radio buttons, and buttons.

Here are some of the most commonly used form attributes in HTML along with coding examples:

action

This attribute is used to define the URL of the page that will process the form data when the form is submitted.

<form action="https://rizwanashiq.com/contact">
<!-- Form fields go here -->
<button type="submit">Submit</button>
</form>

method

This attribute is used to define the HTTP method that will be used when the form is submitted.

<form action="https://rizwanashiq.com/contact" method="post">
<!-- Form fields go here -->
<button type="submit">Submit</button>
</form>

enctype

This attribute is used to define the encoding type that will be used when the form is submitted.

<form
action="https://rizwanashiq.com/contact"
method="post"
enctype="multipart/form-data"
>
<!-- Form fields go here -->
<button type="submit">Submit</button>
</form>

target

This attribute is used to define where to display the response that is received after submitting the form.

<form action="https://rizwanashiq.com/contact" method="post" target="_blank">
<!-- Form fields go here -->
<button type="submit">Submit</button>
</form>

autocomplete

This attribute is used to define whether or not the browser should autocomplete the form fields.

<form action="https://rizwanashiq.com/contact" method="post" autocomplete="off">
<!-- Form fields go here -->
<button type="submit">Submit</button>
</form>

novalidate

This attribute is used to define whether or not the browser should validate the form fields when the form is submitted.

<form action="https://rizwanashiq.com/contact" method="post" novalidate>
<!-- Form fields go here -->
<button type="submit">Submit</button>
</form>

required

This attribute is used to define whether or not a form field is required.

<input type="text" required />

autofocus

This attribute is used to define whether or not a form field should automatically receive focus when the page loads.

<input type="text" autofocus />

placeholder

This attribute is used to define a short hint that describes the expected value of a form field.

<input type="text" placeholder="Enter your name" />

This will give the following result:

disabled

This attribute is used to define whether or not a form field is disabled.

<input type="text" disabled />

This will give the following result:

readonly

This attribute is used to define whether a form field is read-only.

<input type="text" readonly />

This will give the following result:

maxlength

This attribute is used to define the maximum number of characters allowed in a form field.

<input type="text" maxlength="10" />

This will give the following result:

minlength

This attribute is used to define the minimum number of characters allowed in a form field.

<input type="text" minlength="10" />

This will give the following result:

Link attributes are used to define the behavior of links. Here are some of the most commonly used link attributes in HTML along with coding examples:

href

This attribute is used to define the URL of the page the link goes to.

<a href="https://rizwanashiq.com">Rizwan Ashiq</a>

This will give the following result:

target

This attribute is used to define where to display the linked URL.

<a href="https://rizwanashiq.com" target="_blank">Rizwan Ashiq</a>

This will give the following result:

Image Attributes

Image attributes are used to define the behavior of images. Here are some of the most commonly used image attributes in HTML along with coding examples:

src

This attribute is used to define the URL of the image.

<img src="https://docs.rizwanashiq.com/img/logo.svg" />

alt

This attribute is used to define an alternate text for an image, if the image can't be displayed.

<img src="https://docs.rizwanashiq.com/img/logo.svg" alt="Rizwan Ashiq" />

width

This attribute is used to define the width of an image.

<img src="https://docs.rizwanashiq.com/img/logo.svg" width="100" />

height

This attribute is used to define the height of an image.

<img src="https://docs.rizwanashiq.com/img/logo.svg" height="100" />

Styling Tables (Legacy Attributes vs CSS)

Older versions of HTML (HTML4 and earlier) styled tables with presentational attributes like border, cellpadding, cellspacing, align, bgcolor, width, and height. These attributes are obsolete in modern HTML — presentation now belongs in CSS. You will still see them in old tutorials and legacy code, so here is how to achieve the same results with CSS.

Legacy attributeModern CSS equivalent
border="1"border: 1px solid black; on the table and cells
cellpadding="10"padding: 10px; on th/td
cellspacing="10"border-spacing: 10px; on the table
width="100%" / height="100%"width: 100%; / height: 100%;
align="center"margin: 0 auto; on the table
bgcolor="#f1f1f1"background-color: #f1f1f1;

Borders and cell padding

Use the CSS border property on the table and its cells, and padding for the space between cell content and its border. border-collapse: collapse merges the cell borders into single lines (the modern replacement for cellspacing="0"):

<table style="border-collapse: collapse">
<tr>
<th style="border: 1px solid black; padding: 10px">First Name</th>
<th style="border: 1px solid black; padding: 10px">Last Name</th>
</tr>
<tr>
<td style="border: 1px solid black; padding: 10px">Rizwan</td>
<td style="border: 1px solid black; padding: 10px">Ashiq</td>
</tr>
</table>

This will give the following result:

First NameLast Name
RizwanAshiq

Cell spacing

Use border-spacing on the table to control the space between cells:

<table style="border-spacing: 10px">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<td>Rizwan</td>
<td>Ashiq</td>
</tr>
</table>

Width and height

Use the CSS width and height properties to size the table:

<table style="width: 100%; height: 100px">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<td>Rizwan</td>
<td>Ashiq</td>
</tr>
</table>

Alignment

Center a table horizontally with automatic margins:

<table style="margin: 0 auto">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<td>Rizwan</td>
<td>Ashiq</td>
</tr>
</table>

Background color

Use the CSS background-color property:

<table style="background-color: #f1f1f1">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<td>Rizwan</td>
<td>Ashiq</td>
</tr>
</table>
tip

Inline style attributes are used here to keep the examples self-contained. In real projects, put these rules in a stylesheet with a class or element selector instead.

Common Mistakes to Avoid ⚠️

1. Forgetting Quotes

<!-- ❌ Wrong - breaks with spaces -->
<img alt=A beautiful sunset>

<!-- ✅ Right -->
<img alt="A beautiful sunset">

2. Duplicate IDs

<!-- ❌ Wrong - same ID twice -->
<div id="box">First</div>
<div id="box">Second</div>

<!-- ✅ Right - unique IDs -->
<div id="box1">First</div>
<div id="box2">Second</div>

3. Attributes in Closing Tags

<!-- ❌ Wrong -->
<p>Text</p class="highlight">

<!-- ✅ Right -->
<p class="highlight">Text</p>

4. Wrong Quote Mixing

<!-- ❌ Wrong - mixed quotes -->
<img src="photo.jpg' alt='A cat">

<!-- ✅ Right - consistent quotes -->
<img src="photo.jpg" alt="A cat">

Key Takeaways 🎯

Remember: ✅ Attributes customize HTML elements ✅ Always in the opening tag ✅ Format: name="value" ✅ Global attributes work on any element ✅ Specific attributes only on certain elements

Essential attributes to master:

<!-- Identification -->
<div id="unique-element"> Unique identifier
<div class="reusable-style"> Grouping & styling

<!-- Images -->
<img src="photo.jpg" alt="Cat"> Source & description

<!-- Links -->
<a href="page.html">Link</a> Destination

<!-- Forms -->
<input type="text" placeholder="Name" required>

<!-- Styling -->
<p style="color: red;">Text</p> Inline CSS

<!-- Interactivity -->
<button onclick="doSomething()"> JavaScript events

Next steps:

  • Practice adding attributes to your HTML
  • Experiment with different attribute combinations
  • Learn CSS to make full use of class and id
  • Explore JavaScript to leverage id for interactivity

You're now ready to create dynamic, interactive web pages! 🚀

Quick Reference Card 📋

<!-- Structure & Identification -->
<element id="unique"> One per page
<element class="style1 style2"> Reusable, multiple OK

<!-- Styling -->
<element style="color: red;"> Inline CSS
<element title="Tooltip"> Hover text

<!-- Links & Images -->
<a href="url" target="_blank"> Link destination & window
<img src="file.jpg" alt="Desc"> Image source & description

<!-- Forms -->
<input type="text" Input type
placeholder="Hint" Hint text
required Must fill
disabled> Can't edit

<!-- Events -->
<button onclick="fn()"> Click handler
<input onchange="fn()"> Change handler

<!-- Visibility -->
<div hidden> Hide element
<div contenteditable="true"> Make editable