/

Understanding the HTML `a` Tag: A Comprehensive Guide

Understanding the HTML a Tag: A Comprehensive Guide

Learn the essential aspects of working with the HTML a tag to create effective and user-friendly links.

Links in HTML are created using the a tag, with the link destination specified by its href attribute.

Let’s take a look at an example:

1
<a href="https://flaviocopes.com">click here</a>

In the above example, we have an absolute URL. However, links can also work with relative URLs:

1
<a href="/test">click here</a>

In this case, when the user clicks the link, they will be redirected to the /test URL within the current origin.

It’s important to be cautious with the use of the / character. If omitted, instead of starting from the origin, the browser will append the test string to the current URL. For instance, consider the following example, where I’m currently on the page https://flaviocopes.com/axios/:

  • /test - once clicked, it will navigate to https://flaviocopes.com/test.
  • test - once clicked, it will navigate to https://flaviocopes.com/axios/test.

Interestingly, the a tag can include elements other than just text. For instance, you can embed images within link tags:

1
2
3
<a href="https://flaviocopes.com">
<img src="test.jpg">
</a>

You can include any other elements, except for additional <a> tags, within link tags.

If you wish to open the link in a new tab, you can utilize the target attribute:

1
<a href="https://flaviocopes.com" target="_blank">open in new tab</a>

Tags: HTML, a tag, links, href attribute, relative URLs, absolute URLs, target attribute