Fill your College Details

Summarise With AI
ChatGPT
Perplexity
Claude
Gemini
Grok
ChatGPT
Perplexity
Claude
Gemini
Grok
Back

How to Use Anchor Tag in HTML with Examples

08 Sep 2025
5 min read

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 blog will cover everything you need to know about the anchor tag in HTML. You’ll learn what it is, how it works, and the difference between anchor tags and hyperlinks. We’ll walk through key attributes, syntax, and practical uses, such as linking to external or internal pages, jumping within the same page, and creating bookmarks. You’ll also see examples, styling tips with CSS, interactivity with JavaScript, and best practices for accessibility. By the end, you’ll be ready to use anchor tags confidently in your projects.

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.

🎯 Calculate your GPA instantly — No formulas needed!!

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.

Anchor tags also support different types of links:

  • Links to external websites using absolute URLs
<a href="https://www.google.com">Visit Google</a>
  • Links to other pages within the same site using relative paths
<a href="about.html">About Us</a>
  • In-page navigation to specific sections using ID references
<!-- Link -->
<a href="#contact">Go to Contact Section</a>

<!-- Target section -->
<h2 id="contact">Contact Us</h2>
  • Email links using the mailto: protocol
<a href="mailto:info@example.com">Send Email</a>
  • Phone links using the tel: protocol
<a href="tel:+1234567890">Call Us</a>
  • JavaScript functionality triggers
<a href="javascript:void(0);" onclick="alert('Hello, world!')">Click Me</a>

The anchor tag remains a crucial HTML element that connects the massive network of web pages. It creates the connected experience we rely on while browsing the internet.

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:

  • Text links (the most common type)
  • Image links that take you to another location when clicked
  • Button-like elements that trigger navigation
  • Area links within images (image maps)

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).

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 (<a>)
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. Let's get into the exact syntax that makes hyperlinks work in HTML documents.

An anchor tag has three simple parts:

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

The opening <a> tag starts the anchor element. The href attribute (hypertext reference) tells browsers where to go when users click the link. The closing </a> tag wraps up the element. Any content between these tags becomes clickable text for users.

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.

Here are some examples that show proper anchor tag syntax:

For external links using absolute URLs:

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

For internal pages using relative paths:

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

For same-page navigation using fragment identifiers:

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

Browsers turn the text between tags into clickable links. A click directs users to the URL specified in the href attribute.

Anchor names follow specific rules. Each anchor name in a document must be unique. The matching between fragment identifiers and anchor names is case-sensitive.

HTML doesn't allow nested links - you can't put one anchor element inside another.

You can create an anchor at any element's start tag using the id attribute, even within the anchor tag itself. The id and name attributes share the same namespace. This means you can't use similar names to define different anchors in one document.

This simple syntax equips you to create all kinds of links - from basic page navigation to detailed in-document references.

How to Use the HTML Anchor Tag?

Let's look at practical ways to use anchor tag in HTML documents now that you know their syntax. 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 - These 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 - These 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">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">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">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</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:someone@example.com">Send email</a>

You can include body text and a subject line:

<a href="mailto:email@example.com?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. Let's dissect these attributes to understand what they mean for HTML development.

href, target, title, rel attributes

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:example@domain.com">Email us</a>
<a href="sms:+1234567890">Text us</a>

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

  • _self: Opens in the same browsing context (default)
  • _blank: Opens in an entirely new window or tab
  • _parent: Opens in the parent browsing context
  • _top: Opens in the full browser window

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

<a href="page.html">Services</a>

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

  • nofollow: requests that search engines not click on the link.
  • noopener: Prevents the new page from accessing the opener window
  • noreferrer: Prevents passing referrer information
  • alternate: Indicates an alternate version of the document

ping attribute for tracking clicks

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

<a href="https://example.com">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:

  • :link - Styles for unvisited links
  • :visited - Styles for links users have clicked
  • :hover - Styles when users move their cursor over the link
  • :focus - Styles when the link receives keyboard focus
  • :active - Styles during the actual click

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 */

To name just one example, see how 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="#">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">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

  1. Avoid vague words like “click here” or “read more.”
  2. Write text that makes sense even without context.

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

  1. Make note of links that open in a new tab or window (target="_blank") in the content.
  2. Example: “Company Blog (opens in new tab)”
  3. For downloadable files, include the file type: “Annual Report (PDF)”.

3. Ensure keyboard accessibility

  1. Links should be reachable using the Tab key.
  2. Provide a visible focus indicator (outline, highlight) so users know which link is active.
  3. Add skip links at the top to let keyboard users jump directly to the main content.

4. Make links visually distinct

  1. Don’t rely only on color to show links.
  2. Underlines or other visual cues help people with color vision deficiencies identify clickable elements.

5. Support assistive technology

  1. Screen readers rely on meaningful anchor text. Always write links as if they’ll be read aloud without surrounding context.
  2. Tooltips (title attribute) can add extra info but should never replace clear link text.

6. SEO and usability benefits

  1. In addition to being beneficial to visitors, accessible links also improve navigation and rankings by assisting search engines in comprehending the relations among your pages.

Use Cases of Accessible Anchor Tags

  • Download links

Example:

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

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

  • External resources 

Example:

<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

Example:

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

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

  • In-page jumps

Example:

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

Makes long pages easier to navigate without endless scrolling.

  • Contextual guides

Example:

<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.

  • Basic syntax requires href attribute: Use <a href="destination">Link Text</a> structure - without href, anchor tags become non-functional placeholders 
  • Multiple link types serve different purposes: Create external links with absolute URLs, internal navigation with relative paths, and same-page jumps using fragment identifiers (#) 
  • Enhance functionality with key attributes: Use target="_blank" for new tabs, download for file downloads, and mailto: or tel: for email and phone links 
  • Prioritize accessibility with descriptive text: Avoid vague phrases like "click here" - use clear, standalone descriptions that make sense to screen reader users 
  • Style strategically while maintaining usability: Customize appearance with CSS pseudo-classes (:hover, :visited, :active) but ensure links remain visually distinct and keyboard accessible

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.

Read More Articles

Chat with us
Chat with us
Talk to career expert