How to Use Anchor Tag in HTML with Examples

Published: 08 Sep 2025 | Reading Time: 5 min read

Overview

The anchor tag in HTML is one of the building blocks of the web. Without it, websites would just be isolated pages with no easy way to move around. Any clickable link you see - text, an image, a button - is dependent on an anchor tag to take you to another page, a specified section on the page, or even other resources externally. In simple words, the anchor tag makes the internet "clickable," turning static content into an interactive experience that keeps users moving from one place to another.

This comprehensive guide covers everything you need to know about the anchor tag in HTML, including what it is, how it works, the difference between anchor tags and hyperlinks, key attributes, syntax, practical uses, styling with CSS, interactivity with JavaScript, and best practices for accessibility.

Table of Contents

What is an Anchor Tag in HTML?

The anchor tag (<a>) stands as a core HTML element that shapes how users move through the web. It creates hyperlinks that connect web pages, files, email addresses, and even different sections on the same page.

Anchor Tag Attributes

The <a> (anchor) tag supports several attributes that define how a link works and behaves:

Attribute Description Example
href Defines the URL or path the link points to. <a href="https://example.com">Visit Example</a>
target Specifies where to open the link. Common values: _self (same tab), _blank (new tab). <a href="page.html" target="_blank">Open in new tab</a>
title Adds extra info that shows as a tooltip on hover. <a href="about.html" title="Learn more about us">About</a>
download Lets users download the linked file instead of opening it. <a href="file.pdf" download>Download PDF</a>
rel Explains the connection between the link and the current page. nofollow, noopener, and noreferrer are typical values. <a href="https://example.com" rel="nofollow">External Link</a>
id Gives a unique ID to the link, often used for bookmarks or internal linking. <a id="contact">Contact Section</a>
class Assigns class names for CSS styling or JavaScript. <a href="home.html" class="nav-link">Home</a>

Definition and Purpose of Anchor Tags

HTML uses the <a> element as an anchor tag that works as the basic building block of hypertext—a network of connected documents that make up the web. The HTML specification states that an anchor marks where a hypertext link starts and ends. Users can click any content between the opening <a> and closing </a> tags to reach the link's destination.

The web wouldn't exist as we know it without anchor tags. These tags serve three main purposes:

  1. Creating connections - They build pathways between different documents and resources online
  2. Enabling navigation - A simple click lets users jump between pages
  3. Organizing information - They build relationships between related content pieces

The href attribute must exist in an anchor tag to create an active link. Without this attribute, the tag just sits there as a placeholder with no linking ability.

Why Do We Use the Anchor Tag in HTML?

Developers add an anchor tag in HTML code for several key reasons:

Anchor tags turn static websites into interactive experiences. Users can explore content based on what interests them and find new information, resources, or take specific actions with a simple click.

These tags boost search engine optimization substantially. Links help search engines discover new pages to crawl. The anchor text within these tags gives search engines context about the linked content, which helps improve page rankings.

User experience gets better through visual hints that anchor tags provide. Browsers show unvisited links in blue with an underline, purple for visited links, and red for active ones. This consistent visual system helps users spot clickable elements and track their browsing history.

Types of Links Created with Anchor Tags

Anchor tags support different types of links:

External Website Links (Absolute URLs):

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

Internal Page Links (Relative Paths):

<a href="about.html">About Us</a>

In-Page Navigation (ID References):

<!-- Link -->
<a href="#contact">Go to Contact Section</a>

<!-- Target section -->
<h2 id="contact">Contact Us</h2>

Email Links (mailto: Protocol):

<a href="mailto:[email protected]">Send Email</a>

Phone Links (tel: Protocol):

<a href="tel:+1234567890">Call Us</a>

JavaScript Functionality Triggers:

<a href="javascript:void(0);" onclick="alert('Hello, world!')">Click Me</a>

What is a Hyperlink?

A clickable link that connects one web resource to another, be it a separate webpage, a piece of the same page, or even an email or file, is called a hyperlink. The Web follows Tim Berners-Lee's original vision with three core elements: URLs to address documents, HTTP to transfer them, and HTML with embedded hyperlinks to connect them all together.

Understanding Hyperlinks in Web Navigation

Hyperlinks, or simply "links," give users direct access to data with a single click or tap. You'll spot them by their distinct appearance—unvisited links are typically blue and underlined, visited ones turn purple, and active links show up in red. Your cursor turns into a hand icon when it hovers over these clickable elements.

These interactive elements come in several forms:

We use hyperlinks to move smoothly between webpages. They create the basic navigation system of the internet. The concept of "web surfing" exists because of these links. Users can jump between documents instantly instead of typing long URLs manually.

Hyperlinks function through hypertext (HTML or XML code) that points to the destination address. The browser reads the underlying code and takes you to the specified location when you click the visible part (anchor text).

Difference Between Hyperlinks and Anchor Tag in HTML

Although people often use the terms interchangeably, hyperlinks and anchor tags are not the same. A hyperlink is the clickable link itself, while the anchor tag is the HTML code that creates it.

Aspect Hyperlink Anchor Tag ()
Meaning A clickable connection that lets users move from one resource to another. The HTML element used to create a hyperlink in a webpage.
Scope A broader concept that exists across the web. A technical implementation inside HTML code.
Role What users see and interact with (text, image, button). What developers use to define the link and its behavior.
Attributes Doesn't have attributes on its own—just the idea of a link. Uses attributes like href, target, and rel to control link behavior.
Types Can be internal, external, inbound, or anchor (same-page). Creates all these types through HTML code.
Dependency It cannot exist on a webpage without being implemented. Necessary to make hyperlinks functional in HTML.

Syntax of Anchor Tag in HTML

HTML anchor tags are the foundation of web navigation. The exact syntax that makes hyperlinks work in HTML documents consists of three simple parts:

<a href="destination-url">Link Text</a>

Components of Anchor Tag Syntax

  1. Opening <a> tag - Starts the anchor element
  2. href attribute (hypertext reference) - Tells browsers where to go when users click the link
  3. Link text - Content between opening and closing tags that becomes clickable
  4. Closing </a> tag - Wraps up the element

Anchor tags differ from other HTML elements like <img> that use a src attribute. They specifically need href to define where links should go. Without this attribute, the anchor tag becomes just a placeholder that won't take users anywhere.

The link text between opening and closing tags plays a vital role. It tells users what they'll find when they click.

Syntax Examples

External Links (Absolute URLs):

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

Internal Pages (Relative Paths):

<a href="/about.html">About Us</a>

Same-Page Navigation (Fragment Identifiers):

<a href="#contact">Jump to Contact</a>

Important Syntax Rules

How to Use the HTML Anchor Tag?

Let's look at practical ways to use anchor tag in HTML documents. Links are the foundations of good web navigation.

Linking to External Pages Using Absolute URLs

External links take users to websites outside your domain. You'll need absolute URLs with complete web addresses for these links. The structure looks like this:

<a href="https://www.expert.com">Visit Expert Website</a>

The protocol (https://), domain name (www.expert.com), as well as particular pathways (/about/team.html) are required for absolute URLs. Shifting from HTTP to HTTPS improves website security and can also enhance performance.

Linking to Internal Pages Using Relative Paths

Relative URLs work better when you link to pages within your website. These come in two types:

1. Root-relative paths - Start with a forward slash and link from your domain's root:

<a href="/products/new-arrivals.html">See New Products</a>

2. Document-relative paths - Link from your current document's location:

<a href="../contact.html">Contact Us</a>

The ../ notation takes you up one directory level. Using just the filename points to a page in your current directory.

Jumping to Sections on the Same Page

With in-page navigation, users may navigate between sections of a lengthy webpage with ease. Here's how to do it:

<!-- Link to the section -->
<a href="#section2">Jump to Section 2</a>

<!-- The target section (elsewhere on the page) -->
<div id="section2">
    <h2>Section 2 Content</h2>
    <p>This is the place of section 2 content.</p>
</div>

A fragment identifier consists of a hash symbol (#) followed by the element's ID.

Creating Bookmarks with id Attribute

Bookmarks help users find specific content on your page quickly. Modern HTML uses the id attribute instead of the older name attribute to create these anchors:

<!-- Creating the bookmark -->
<h2 id="important-info">Important Information</h2>

<!-- Linking to the bookmark from elsewhere -->
<a href="#important-info">Go to Important Information</a>

You can also link to bookmarks on other pages by combining your URL with fragment identifiers:

<a href="https://example.com/page.html#specific-section">Go to Specific Section</a>

The id attribute needs to be unique in your document. You can use it with almost any HTML element, which makes it very flexible for page navigation.

Examples of the Anchor Tag HTML in Action

Anchor tags go beyond simple linking by offering powerful features through specialized attributes and values. Let's look at some practical ways to extend what HTML anchor tags can do.

Opening Links in a New Tab Using target="_blank"

The target attribute controls where linked content appears after a user clicks. Links can be viewed in a separate window or tab in your browser:

<a href="https://www.expert.com" target="_blank">Visit Expert Website</a>

This works great to help users keep their place on your site. For security reasons, you should pair target="_blank" with rel="noopener noreferrer" to avoid potential vulnerabilities:

<a href="https://www.expert.com" target="_blank" rel="noopener noreferrer">Visit Expert Website</a>

Today's browsers automatically set rel=noopener for links with target=_blank, but including it explicitly ensures better compatibility across all browsers.

Downloadable Links Using download Attribute

HTML5's download attribute turns regular links into file download triggers:

<a href="button.png" download>Click Here to Download the Image</a>

You can set custom filenames by giving the attribute a value:

<a href="/images/myw3schoolsimage.jpg" download="W3Schools_Logo.jpg">Download W3Schools Logo</a>

The download attribute works with same-origin URLs, blob:, and data: schemes.

Email and Phone Links Using mailto: and tel:

Email Links launch the user's default email client with a pre-addressed message:

<a href="mailto:[email protected]">Send email</a>

You can include body text and a subject line:

<a href="mailto:[email protected]?subject=Subject%20Line&body=This%20is%20the%20body%20text">Email Us</a>

Phone Links let mobile users make calls right away:

<a href="tel:+1(800)555-0123">(800) 555-0123</a>

JavaScript Execution Using href="javascript:"

You can execute JavaScript functions through anchor tags:

<a href="javascript:alert('This is a demo alert')">Click Me</a>

Another option is to call a defined function:

<a href="javascript:notifyUser()">Click the Link</a>

These methods run JavaScript directly through links, but using proper event handlers in production environments gives you better separation of concerns.

Learn More About Anchor Tag in HTML Attributes

The anchor tag's attributes are what give it its real power. These special modifiers control how links behave, look and interact with both users and systems.

href, target, title, rel Attributes

href Attribute:

A functioning anchor tag needs the href attribute as its foundation to define where the URL points to. The anchor tag won't work as a link without this attribute. The URL can point to more than just web pages:

<a href="tel:+1234567890">Call us</a>
<a href="mailto:[email protected]">Email us</a>
<a href="sms:+1234567890">Text us</a>

target Attribute:

The target attribute controls where your linked content shows up after a click. You can use these values:

title Attribute:

Users see extra information about the link through the title attribute. This shows up as a tooltip on hover:

<a href="page.html" title="View our services">Services</a>

rel Attribute:

The rel attribute shows how the current document connects to the linked document. Some common values:

ping Attribute for Tracking Clicks

The ping attribute makes it easy to track link clicks through asynchronous POST requests:

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

The browser sends background POST requests to specified URLs when someone clicks this link. Chrome and Safari fully support this feature, while Firefox keeps it behind a configuration flag.

id vs name Attribute for In-Page Navigation

Developers used the name attribute to create anchors within pages:

<a name="section">Section Heading</a>

Modern HTML prefers the id attribute:

<h2 id="section">Section Heading</h2>

Both attributes work for in-page navigation in older browsers. The id attribute works better because you can use it with any HTML element, not just anchor tags. The name attribute isn't recommended anymore for anchor identification.

Styling Anchor Tags with CSS

Visual presentation of anchor tags plays a vital role in user experience, beyond just their functionality. You can transform ordinary links into design elements that match your website's look through CSS customization while keeping them usable.

Default Link Styles

Browsers apply standard default styles to anchor tags. Links look different from regular text without any CSS styling. Blue underlined text shows unvisited links, purple indicates visited links, and red appears during clicks. Users identify clickable elements easily across the web thanks to this visual pattern.

Hovering over links gives you an additional visual hint by changing your cursor to a hand pointer. Because users are familiar with these visual cues, these default styles from the early days of the web have mostly remained unmodified.

Using :hover, :visited, :active Pseudo-Classes

CSS provides special pseudo-classes to target different link states:

The sequence of these pseudo-classes matters a lot in your CSS. The "LVHA" order (Link, Visited, Hover, Active) helps avoid specificity conflicts where styles might clash:

a:link { color: #6900ff; }
a:visited { color: #a5c300; }
a:hover { text-decoration: none; background: #cdfeaa; }
a:active { background: #6900ff; color: #cdfeaa; }

Removing Underline and Changing Colors

Think over what visual elements show clickability best before removing the default underline. The text-decoration property modifies or removes the underline:

a { text-decoration: none; } /* Removes underline from all links */

Button-like links come to life by combining multiple properties:

a {
  color: white;
  background-color: #FF8A00;
  padding: 10px 15px;
  border-radius: 5px;
  text-decoration: none;
  font-weight: bold;
}

These styles create interactive elements with hover effects:

a:hover {
  background-color: #555;
  transition: background-color 0.3s ease-in-out;
}

Accessibility should guide your link styling choices. Links need a good color contrast with regular text when you remove underlines. Bold text or background colors can serve as alternative indicators.

Interactive Anchors with JavaScript

JavaScript makes anchor tags more powerful by enabling interactive experiences. These elements become dynamic interface components that react to user actions, going beyond basic navigation.

onclick Event for Dynamic Behaviour

Users can trigger JavaScript code through the onclick event handler when clicking an anchor tag. This creates interactive elements without refreshing the page:

<a href="#" onclick="myFunction()">Click me</a>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Text changed!";
}
</script>

The event can be attached directly to the anchor tag as shown above. A better approach separates concerns by binding the event programmatically with JavaScript:

document.getElementById("myLink").onclick = function() {
  // Your code here
};

Preventing Default Behavior with return false

Anchor tags typically navigate to their href destination when clicked. The default action stops by adding return false at the end of your onclick function:

<a href="https://example.com" onclick="myFunction(); return false;">Click me</a>

This method was standard before HTML5. Modern development prefers the more reliable preventDefault() method:

document.getElementById("myLink").onclick = function(event) {
  event.preventDefault();
  // Your code here
};

Using Anchor Tags to Trigger JavaScript Functions

JavaScript functions execute directly through the anchor tag's href attribute:

<a href="javascript:notifyUser()">Notify Me</a>

The notifyUser() function runs right after a user clicks this link. While this works well for quick prototypes, modern development best practices recommend event listeners for better code maintenance.

Accessibility and Best Practices

Anchor tags aren't just about navigation; they also play a big role in making websites usable for everyone, including people with disabilities. When creating links, the way you write and style them directly affects how users (and assistive technologies like screen readers) experience your site.

Key Best Practices

1. Use Clear and Descriptive Link Text

Example:

<!-- Poor example -->
<a href="pricing.pdf">Click here</a>

<!-- Better example -->
<a href="pricing.pdf">Download pricing guide</a>

2. Inform Users About Link Behavior

3. Ensure Keyboard Accessibility

4. Make Links Visually Distinct

5. Support Assistive Technology

6. SEO and Usability Benefits

Use Cases of Accessible Anchor Tags

Download Links:

<a href="syllabus.pdf">Download Course Syllabus (PDF)</a>

Helps users know exactly what they're getting and the file type.

External Resources:

<a href="https://example.com" target="_blank">Visit Our Blog (opens in new tab)</a>

Informs users that the link will open in a new tab, avoiding surprises.

Navigation Aids:

<a href="#main-content">Skip to Main Content</a>

Gives keyboard and screen reader users a quick way to bypass menus.

In-Page Jumps:

<a href="#top">Back to Top</a>

Makes long pages easier to navigate without endless scrolling.

Contextual Guides:

<a href="/accessibility-guide">Read Our Web Accessibility Guide</a>

Uses meaningful text instead of vague phrases like "Read More."

Conclusion

This guide has shown how anchor tag in HTML work as the foundation of web navigation. They make the "H" in HTML—hypertext—possible. These fundamental elements create the interconnected web experience we take for granted today. Without doubt, becoming skilled at anchor tags lets you build smooth navigation experiences for your website's visitors.

The <a> element does more than just link pages together. Anchor tags create different link types - from external website references with absolute URLs to internal page navigation using relative paths. They let users jump to specific sections on the same page, launch email clients, make phone calls, and run JavaScript functions.

The basic syntax <a href="destination">Link Text</a> serves as the foundation. Attributes like target, rel, download, and title substantially boost functionality. The href attribute is vital because your anchor tag becomes plain text without linking abilities if it's missing.

Styling holds equal importance in anchor tag usage. Browsers come with default styles (blue for unvisited links, purple for visited ones). You can create more appealing and user-friendly navigation systems by customizing these styles with CSS pseudo-classes (:link, :visited, :hover, :active).

When implementing anchor tags, accessibility should be your top priority. All users benefit from clear, informative link language, but those who use assistive technologies or screen readers will benefit most. Good keyboard navigation support ensures users can use your links effectively, whatever their interaction method.

Next time a link catches your click, pause to appreciate this simple yet powerful HTML element that makes it all work. This complete knowledge of anchor tags helps you implement various linking strategies in your HTML projects. You can now connect content, improve user experience, and build websites that showcase the web's interconnected nature.

Building your first website or improving your coding skills? Mastering anchor tags marks a key milestone in your development path. These modest HTML elements create the connections that bind the big digital world we direct each day.

Key Takeaways

Master the anchor tag (<a>) to create the hyperlinks that make web navigation possible and transform static HTML into an interconnected web experience.

The anchor tag stands as HTML's most fundamental interactive element, enabling the hypertext connections that define the World Wide Web. Proper implementation combines functional syntax, meaningful attributes, accessible design, and thoughtful styling to create seamless navigation experiences for all users.

Frequently Answered Questions

1. What is the major use of an anchor tag in HTML?

An anchor tag creates hyperlinks that give a user the option to navigate between web pages, files, and sections of the same page. It is the basis for the web experience.

2. How can I create a simple HTML anchor tag?

An anchor tag's basic syntax is <a href="destination-url">Link Text</a>. Whereas the text between the opening and closing tags is what users view and click, the href property indicates where the link leads.

3. Can anchor tags be used for more than just linking to other web pages?

Yes, anchor tags are versatile. They can create links to external websites, internal pages, specific sections within a page, email addresses, phone numbers, and even trigger JavaScript functions.

4. How can I make my anchor tags more accessible?

Use clear, descriptive link text that makes sense out of context. Avoid vague phrases like "click here." For links opening in new tabs, indicate this behavior. Ensure proper color contrast and maintain keyboard accessibility.

5. How do I style anchor tags to match my website's design?

You can customize anchor tag appearance using CSS. Use pseudo-classes like :link, :visited, :hover, and :active to style different link states. You can change colors, remove underlines, add background colors, or even create button-like links while ensuring they remain visually distinct from regular text.