LearnContact
Lesson 88 min read

HTML Attributes

Learn what HTML attributes are, how they provide additional information to elements, and understand common attributes like href, src, alt, id, and class.

Introduction

In the previous lesson, you learned about HTML elements and how they form the building blocks of every webpage.

Elements define the structure and meaning of content. A heading element creates a heading, a paragraph element creates a paragraph, and an image element represents an image.

However, the element name alone is often not enough.

A link needs to know where it should navigate. An image needs to know which file it should display. A form control may need to know whether it is required, disabled, or ready to accept a particular type of data.

HTML attributes provide this additional information.

HTML Element
Add Attribute
Provide Additional Information
Browser Interprets Settings
Element Behaves Accordingly
Element with an Attribute
<a href="https://example.com">Visit Website</a>
Elements Define, Attributes Configure

The element identifies what the content is, while attributes provide additional information or configuration for that element.

What are HTML Attributes?

HTML attributes provide additional information, settings, or configuration for HTML elements.

They can affect the behavior, meaning, accessibility, identification, or functionality of an element.

Attributes are written inside the opening tag or start tag of an HTML element.

Element Without an Attribute
<a>Visit Website</a>

This creates an anchor element, but it does not specify a destination.

Element With an Attribute
<a href="https://example.com">Visit Website</a>

The href attribute provides the destination that the link should navigate to.

Element and Attribute
<a href="https://example.com">Visit Website</a>
 │     │             │             │
 │     │             │             │
 ▼     ▼             ▼             ▼
Element Attribute   Value         Content

Configuration

Attributes provide settings for elements.

Resources

Attributes can specify destinations and external files.

Identification

Attributes can identify or group elements.

Accessibility

Some attributes provide information used by assistive technologies.

Key Point

Attributes provide extra information about an element and are written inside its start tag.

Why Do We Need Them?

HTML elements describe the type of content, but many elements require additional information before they can perform their intended purpose.

Without Attributes

  • A link does not know its destination.
  • An image does not know which resource to load.
  • Elements cannot be uniquely identified with an id.
  • Elements cannot be grouped using class names.
  • Form controls cannot receive many important settings.

With Attributes

  • Links can specify destinations.
  • Images can specify source files.
  • Elements can have identifiers.
  • Elements can be grouped for styling and scripting.
  • Form controls can receive additional configuration.

Define Destinations

The href attribute tells a link where to navigate.

Load Resources

The src attribute tells certain elements which resource to load.

Add Alternatives

The alt attribute provides a text alternative for images.

Identify Elements

The id attribute can uniquely identify an element.

Group Elements

The class attribute can associate multiple elements with shared class names.

Configure Forms

Attributes define input types, requirements, values, and other behavior.

Create Element
Add Required Attributes
Provide Values
Browser Processes Configuration
Element Performs Its Purpose

Real-World Analogy

Imagine a student in a school.

The student is the main object, similar to an HTML element. However, the school also stores additional information about that student.

Student Record Analogy
Student                    ← HTML Element
│
├── Name                   ← Attribute
├── Roll Number            ← Attribute
├── Class                  ← Attribute
├── Photo                  ← Attribute
└── Admission Number       ← Attribute

The student remains the main object, while the additional details describe or configure information associated with that student.

HTML works in a similar way.

HTML Example
<img
    src="student.jpg"
    alt="Student Profile Photo"
    width="200"
>
HTML Analogy
img Element
│
├── src="student.jpg"
├── alt="Student Profile Photo"
└── width="200"
Element + Additional Details

The element defines the object or document component, while its attributes provide additional information about it.

Attribute Syntax

Most HTML attributes are written as a name followed by an equals sign and a value.

General Attribute Syntax
<tagname attribute="value">
    Content
</tagname>

The attribute appears inside the start tag before the closing angle bracket.

Link Example
<a href="https://example.com">Visit Website</a>
Attribute Syntax Breakdown
<a href="https://example.com">
    │             │
    │             │
    ▼             ▼
Attribute        Attribute
  Name             Value
PartExamplePurpose
Element NameaIdentifies the HTML element
Attribute NamehrefIdentifies the additional setting
Equals Sign=Connects the name and value
Attribute Value"https://example.com"Provides the setting data

Attributes Belong Inside the Start Tag

Correct Placement
<a href="https://example.com">Visit Website</a>
Incorrect Placement
<!-- ❌ Incorrect -->

<a> href="https://example.com" Visit Website</a>
Use Quoted Values

Although HTML syntax allows some unquoted attribute values in specific cases, consistently using quotes makes markup clearer and avoids many parsing problems.

Parts of an Attribute

A typical attribute contains two main parts: an attribute name and an attribute value.

Example Attribute
href="https://example.com"

1️⃣ Attribute Name

Identifies the property or setting being provided. Example: href.

2️⃣ Attribute Value

Provides the data assigned to the attribute. Example: https://example.com.

1. Attribute Name

Attribute Name
href="https://example.com"
 │
 ▼
Attribute Name

The attribute name identifies what additional information or setting is being provided.

2. Attribute Value

Attribute Value
href="https://example.com"
         │
         ▼
   Attribute Value

The attribute value contains the actual information assigned to the attribute.

AttributeNameValue
href="https://example.com"hrefhttps://example.com
src="photo.jpg"srcphoto.jpg
alt="Mountain View"altMountain View
id="main-title"idmain-title
class="card"classcard

Example 1: Link Attribute

The anchor element creates a hyperlink.

The href attribute specifies the destination associated with that link.

Link Attribute
<a href="https://www.google.com">Visit Google</a>
Link Breakdown
<a href="https://www.google.com">Visit Google</a>
 │    │              │              │
 │    │              │              │
 ▼    ▼              ▼              ▼
Anchor Attribute   Destination     Link Text
Element
PartValuePurpose
ElementaRepresents a hyperlink
AttributehrefSpecifies the link destination
Valuehttps://www.google.comThe destination address
ContentVisit GoogleThe visible link text
Link Example
The Attribute Makes the Link Useful

The anchor element represents a hyperlink, while the href attribute provides the destination.

Example 2: Image Attribute

The img element embeds an image into the document.

It commonly uses the src attribute to identify the image resource and the alt attribute to provide a text alternative.

Image Attributes
<img src="nature.jpg" alt="Beautiful Nature">
Image Breakdown
img
│
├── src="nature.jpg"
│      │
│      └── Image resource
│
└── alt="Beautiful Nature"
       │
       └── Text alternative
PartValuePurpose
ElementimgEmbeds an image
srcnature.jpgIdentifies the image resource
altBeautiful NatureProvides a text alternative
The alt Attribute Has an Important Purpose

Alternative text helps communicate the purpose or content of an image when the image cannot be seen or loaded. The correct alt value depends on the purpose of the image.

Not Every Image Needs Descriptive Text

Meaningful images generally need useful alternative text. Purely decorative images commonly use an empty alt value so assistive technologies can ignore them.

Multiple Attributes

An HTML element can contain multiple attributes.

Attributes are separated from each other by whitespace inside the start tag.

Multiple Attributes
<a
    href="https://www.bytecrest.com"
    target="_blank"
    title="Visit Bytecrest"
>
    Bytecrest
</a>
Attribute Collection
a Element
│
├── href="https://www.bytecrest.com"
│
├── target="_blank"
│
└── title="Visit Bytecrest"
AttributeValuePurpose
hrefhttps://www.bytecrest.comSpecifies the destination
target_blankChooses a new browsing context
titleVisit BytecrestProvides advisory information
Separate Attributes with Whitespace

Each attribute is written separately inside the start tag. When an element has many attributes, formatting them across multiple lines can improve readability.

Common HTML Attributes

HTML provides many attributes. Some are specific to particular elements, while global attributes can be used on most HTML elements.

AttributeCommon PurposeExample
hrefSpecifies a hyperlink destinationhref="/about"
srcSpecifies a resource locationsrc="photo.jpg"
altProvides a text alternative for an imagealt="Mountain View"
titleProvides advisory informationtitle="More Information"
idProvides an element identifierid="main-title"
classAssigns one or more class namesclass="card featured"
styleAdds inline CSS declarationsstyle="color: red;"
widthProvides width information for supported elementswidth="300"
heightProvides height information for supported elementsheight="200"

href Attribute

href Example
<a href="/about">About Us</a>

The href attribute specifies the destination of a hyperlink.

src Attribute

src Example
<img src="photo.jpg" alt="Mountain View">

The src attribute identifies a resource to be loaded by supported elements.

alt Attribute

alt Example
<img src="photo.jpg" alt="Snow-covered mountain">

The alt attribute provides a text alternative for an image.

id Attribute

id Example
<h1 id="main-title">Learn HTML</h1>

The id attribute assigns an identifier to an element. An id value should be unique within the document.

class Attribute

class Example
<article class="card featured">
    Featured Article
</article>

The class attribute assigns one or more class names to an element. Multiple elements can share the same class names.

id Attribute

  • Identifies an element.
  • Its value should be unique in the document.
  • Useful for fragment links.
  • Can be used by CSS and JavaScript.

class Attribute

  • Assigns class names.
  • Can be shared by multiple elements.
  • An element can have multiple classes.
  • Commonly used by CSS and JavaScript.

Example 3: Multiple Attributes

The following image element uses several attributes together.

Image with Multiple Attributes
<img
    src="flower.jpg"
    alt="Pink flower in a garden"
    width="300"
    height="200"
    title="Beautiful Flower"
>
Attribute Breakdown
img
│
├── src="flower.jpg"
│
├── alt="Pink flower in a garden"
│
├── width="300"
│
├── height="200"
│
└── title="Beautiful Flower"
AttributeValueRole
srcflower.jpgIdentifies the image resource
altPink flower in a gardenProvides a text alternative
width300Provides width information
height200Provides height information
titleBeautiful FlowerProvides advisory information
Browser Finds img
Reads src
Requests Image Resource
Uses Dimensions
Processes Additional Attributes
Displays Result

Boolean Attributes

Some HTML attributes represent a true-or-false state.

These are called boolean attributes.

For a boolean attribute, the presence of the attribute represents the true state, while its absence represents the false state.

Boolean Attribute
<input type="text" disabled>

Because the disabled attribute is present, the input is disabled.

Without the Boolean Attribute
<input type="text">

Because the disabled attribute is absent, the input is not disabled by that attribute.

Boolean AttributeCommon Use
disabledDisables a supported form control
checkedMarks a checkbox or radio control as checked
readonlyMakes a supported control read-only
requiredMarks a supported form control as required
selectedMarks an option as selected
multipleAllows multiple values where supported
autofocusRequests initial focus
Boolean Attribute Examples
<input type="checkbox" checked>

<input type="text" readonly>

<input type="email" required>

<select>
    <option selected>India</option>
</select>
false Does Not Disable a Boolean Attribute

For HTML boolean attributes, writing disabled="false" still means the disabled attribute is present. To represent the false state, omit the attribute.

Boolean Attribute Behavior
<!-- Still disabled because the attribute is present -->

<input type="text" disabled="false">


<!-- Not disabled by the disabled attribute -->

<input type="text">
Presence Means True

The simplest and clearest form of a boolean attribute is usually the attribute name by itself, such as disabled, required, or checked.

Attribute Order

In general, the order of attributes inside a start tag does not change the meaning of the element.

Order 1
<img
    src="flower.jpg"
    alt="Pink flower"
    width="300"
    height="200"
>
Order 2
<img
    height="200"
    width="300"
    alt="Pink flower"
    src="flower.jpg"
>

Both examples contain the same attributes and values.

Random Attribute Order

  • May still be valid.
  • Can become inconsistent across files.
  • Can make similar elements harder to compare.
  • May reduce readability in large projects.

Consistent Attribute Order

  • Creates predictable markup.
  • Improves readability.
  • Makes code reviews easier.
  • Helps maintain team conventions.
Choose a Consistent Convention

The browser generally does not care about attribute order, but developers benefit from using a consistent and readable convention.

Browser Rendering Flow

When a browser processes an HTML element with attributes, it reads the element and its attributes as part of the document structure.

Read Start Tag
Identify Element
Read Attributes
Parse Attribute Values
Create DOM Element
Apply Element-Specific Behavior
Render or Use the Element
Example
<img
    src="nature.jpg"
    alt="Green forest"
    width="400"
>
Processing Flow
Read <img>
     │
     ▼
Identify Image Element
     │
     ▼
Read src, alt, and width
     │
     ▼
Create img Element in DOM
     │
     ▼
Use src to Request Resource
     │
     ▼
Use Other Attribute Information
     │
     ▼
Render Result
Attributes Become Part of the DOM Element

After parsing the HTML, the browser represents the element and its attributes in the Document Object Model, where CSS and JavaScript can work with them.

Real-World Applications

Attributes are used throughout real-world websites and web applications.

Navigation

href defines destinations for links.

Images

src identifies image resources and alt provides text alternatives.

Forms

type, name, value, required, disabled, and other attributes configure controls.

CSS Styling

class and id values can be used as CSS selectors.

JavaScript

Scripts can find elements and read or update attributes.

Accessibility

Attributes can provide names, alternatives, states, and other useful information.

Media

src, controls, autoplay, muted, and other attributes configure media elements.

Custom Data

data-* attributes can store custom data associated with elements.

Advantages

Adds Configuration

Attributes provide settings that elements need.

Connects Resources

Attributes identify links, images, scripts, stylesheets, and other resources.

Supports Accessibility

Appropriate attributes can communicate alternatives and additional information.

Identifies Elements

id values can identify specific elements.

Groups Elements

class values allow elements to share classifications.

Supports CSS

Attributes provide useful selectors and configuration for presentation.

Supports JavaScript

Scripts can inspect and modify attributes dynamically.

Configures Forms

Attributes control input types, validation, state, and submission information.

  • Provide additional information about elements.
  • Configure element behavior.
  • Specify destinations and external resources.
  • Improve image accessibility through appropriate alternative text.
  • Identify individual elements.
  • Group related elements.
  • Support CSS selection and styling.
  • Support JavaScript interaction.
  • Configure form controls.
  • Represent boolean states.
  • Store custom data with data-* attributes.
  • Help connect HTML with other web technologies.

Common Beginner Mistakes

Forgetting Quotes

Unquoted values can cause problems when they contain spaces or unsupported characters.

Misspelling Attribute Names

A misspelled attribute may not provide the intended behavior.

Using the Wrong Attribute

Different elements use attributes for different purposes.

Duplicate id Values

An id value should uniquely identify one element in a document.

Missing alt Attributes

Images need appropriate alternative text decisions based on their purpose.

Writing disabled="false"

The presence of a boolean attribute represents the true state.

Repeating the Same Attribute

An attribute name should not be duplicated on the same element.

Using Invalid Attributes

Not every attribute is valid or meaningful on every HTML element.

Quotes Around Values
<!-- ❌ Avoid -->

<img src=my holiday photo.jpg>


<!-- ✅ Correct -->

<img src="my-holiday-photo.jpg" alt="Holiday photo">
Misspelled Attribute
<!-- ❌ Incorrect -->

<a hreff="https://example.com">
    Visit Website
</a>


<!-- ✅ Correct -->

<a href="https://example.com">
    Visit Website
</a>
Wrong Attribute
<!-- ❌ Incorrect -->

<img href="photo.jpg">


<!-- ✅ Correct -->

<img src="photo.jpg" alt="Description of photo">
Duplicate id Values
<!-- ❌ Incorrect -->

<h2 id="section-title">First Section</h2>
<h2 id="section-title">Second Section</h2>


<!-- ✅ Better -->

<h2 id="first-section">First Section</h2>
<h2 id="second-section">Second Section</h2>
Boolean Attribute Mistake
<!-- ❌ Still disabled -->

<input type="text" disabled="false">


<!-- ✅ Enabled -->

<input type="text">

Poor Attribute Usage

  • Misspelled names.
  • Wrong attributes for elements.
  • Duplicate identifiers.
  • Missing accessibility information.
  • Misunderstood boolean attributes.

Proper Attribute Usage

  • Correct attribute names.
  • Valid element-attribute combinations.
  • Unique id values.
  • Purposeful accessibility information.
  • Correct boolean attribute handling.

Best Practices

  • Write attributes inside the element start tag.
  • Use lowercase attribute names for consistency.
  • Use quotes around attribute values.
  • Prefer double quotes consistently unless your project uses another convention.
  • Separate multiple attributes with whitespace.
  • Use attributes that are valid and meaningful for the element.
  • Use meaningful id values.
  • Keep id values unique within the document.
  • Use class names for reusable classifications.
  • Provide appropriate alt values for images based on their purpose.
  • Use empty alt values for purely decorative images when appropriate.
  • Do not use disabled="false" to enable an element.
  • Omit a boolean attribute when its state should be false.
  • Avoid duplicate attributes on the same element.
  • Use consistent attribute ordering.
  • Format long start tags across multiple lines when readability improves.
  • Avoid unnecessary inline style attributes when styles belong in CSS.
  • Use data-* attributes for custom application data.
  • Do not invent arbitrary attributes when standard attributes or data-* attributes are appropriate.
  • Validate HTML when attribute behavior is unexpected.
  • Understand the purpose of an attribute before using it.
  • Do not use attributes only because they appear in copied code.
  • Use secure link practices when opening untrusted external pages in new tabs.
  • Keep attribute values meaningful and maintainable.
  • Follow consistent project conventions.
Readable Attribute Formatting
<img
    src="/images/course-cover.jpg"
    alt="HTML course cover"
    width="640"
    height="360"
    class="course-cover"
>
Attributes Should Have a Purpose

Every attribute should provide useful information or configuration. Avoid adding attributes that are unnecessary or do not apply to the element.

Frequently Asked Questions

What is an HTML attribute?

An HTML attribute provides additional information, settings, or configuration for an HTML element.

Where are HTML attributes written?

Attributes are written inside an element start tag.

What are the main parts of a typical attribute?

A typical attribute contains an attribute name and an attribute value.

How are an attribute name and value connected?

They are normally connected using an equals sign.

Should attribute values use quotes?

Using quotes consistently is recommended because it improves readability and avoids problems with values that cannot be safely written without quotes.

Can an element have multiple attributes?

Yes. An element can contain multiple attributes inside its start tag.

How are multiple attributes separated?

They are separated by whitespace.

What does the href attribute do?

The href attribute commonly specifies the destination of a hyperlink.

What does the src attribute do?

The src attribute identifies a resource to be loaded by supported elements.

What does the alt attribute do?

The alt attribute provides a text alternative for an image.

Does every image need the same kind of alt text?

No. The correct alt value depends on the purpose and context of the image.

What should decorative images use for alt?

Purely decorative images commonly use an empty alt value so assistive technologies can ignore them.

What is the id attribute?

The id attribute provides an identifier for an element.

Can two elements use the same id value?

An id value should be unique within a document.

What is the class attribute?

The class attribute assigns one or more class names to an element.

Can multiple elements use the same class?

Yes. Multiple elements can share the same class names.

Can one element have multiple classes?

Yes. Multiple class names can be written in the class attribute value and separated by spaces.

What is a boolean attribute?

A boolean attribute represents a true-or-false state through its presence or absence.

What happens when a boolean attribute is present?

Its state is considered true.

How do I make a boolean attribute false?

Omit the attribute.

Does disabled="false" enable an input?

No. The disabled attribute is still present, so the control remains disabled.

Does attribute order matter?

In general, changing the order of attributes does not change the meaning of the element.

Why should developers use consistent attribute order?

Consistency improves readability, maintainability, and code review.

Can I use any attribute on any element?

No. Some attributes are global, while others apply only to specific elements.

What are global attributes?

Global attributes are attributes that can be used on most HTML elements, such as id, class, and title.

What are data-* attributes?

They are custom data attributes used to store application-specific information on HTML elements.

Can CSS use HTML attributes?

Yes. CSS can select elements using classes, ids, and attribute selectors.

Can JavaScript change attributes?

Yes. JavaScript can read, add, update, and remove attributes through the DOM.

What should I learn after HTML attributes?

The next lesson is HTML headings, where you will learn how to create a structured heading hierarchy.

Key Takeaways

  • HTML attributes provide additional information about elements.
  • Attributes are written inside element start tags.
  • A typical attribute contains a name and a value.
  • The equals sign connects an attribute name with its value.
  • Attribute values should be quoted consistently.
  • An element can contain multiple attributes.
  • Multiple attributes are separated by whitespace.
  • The href attribute commonly defines a hyperlink destination.
  • The src attribute identifies resources for supported elements.
  • The alt attribute provides a text alternative for images.
  • Alternative text should be based on the purpose and context of the image.
  • The id attribute identifies an element.
  • An id value should be unique within the document.
  • The class attribute assigns one or more class names.
  • Multiple elements can share class names.
  • Boolean attributes represent true-or-false states.
  • The presence of a boolean attribute represents true.
  • The absence of a boolean attribute represents false.
  • Writing disabled="false" does not make disabled false.
  • Attribute order generally does not change element meaning.
  • Consistent attribute ordering improves readability.
  • Some attributes are global.
  • Some attributes apply only to specific elements.
  • Attributes support HTML, CSS, JavaScript, forms, accessibility, and resource loading.
  • Correct attribute usage is essential for functional and maintainable webpages.

Summary

HTML attributes extend elements by providing additional information, settings, and configuration.

They are written inside element start tags and commonly use a name-value structure.

You learned how the href attribute specifies link destinations and how src identifies resources used by supported elements.

You also learned how the alt attribute provides a text alternative for images and why its value should depend on the purpose of the image.

Attributes such as id and class help identify and classify elements for use with HTML, CSS, and JavaScript.

An element can contain multiple attributes, and the order of those attributes generally does not change the meaning of the element.

You also learned about boolean attributes, where presence represents the true state and absence represents the false state.

Correct attribute usage is essential because attributes control destinations, resources, accessibility information, identifiers, classifications, form behavior, and many other parts of modern webpages.

In the next lesson, you will learn about HTML headings and how to create a clear hierarchy of page titles and section headings.

Next Lesson →

Headings