The link element is one of the most important HTML elements that requires our extra attention. It is defined with the <a>
element with the following syntax:
1<a href="url">Link Text</a>
Absolute address vs. relative address
The href
attribute points to the destination of the link.
Suppose the destination is on a different website. In that case, the URL should be an absolute address, meaning it should start from the full domain of the target website, continue to the subdirectories, and finally locate the target webpage.
1<a href="https://www.example.com/path/to/index.html">Index Page</a>
Things are a bit more flexible if the target webpage is hosted on the same website.
1<!-- Absolute address -->
2<a href="/path/to/index.html">Index Page</a>
3
4<!-- Relative address -->
5<a href="./path/to/index.html">Index Page</a>
6<a href="../path/to/index.html">Index Page</a>
7<a href="index.html">Index Page</a>
The first example is an absolute address that points to /path/to/index.html
, starting from the root directory of your website, /
.
The next three examples are addresses that are relative to the location of the current page.
./
means "in the current directory", which means the browser will look forpath
in the same directory as the current webpage.../
indicates the parent directory of the current webpage.- Without
./
or../
, the browser will look for the target under the current directory.
In practice, it is not recommended to use relative paths. As your website's structure becomes more complex, it becomes very difficult to maintain so many relative addresses.
If you can, you should always use absolute addresses so that all of your links have a universal reference, the root directory /
.
Link to emails
Besides linking to webpages, the <a>
element can also link to email addresses using mailto:
inside the href
attribute.
1<a href="mailto:johndoe@example.com">Send email</a>
When the user clicks on this link, the email program will open.
Anchor links
Anchor links points to sections of a webpage. They can be useful if the webpage is long and you need to create a table of contents section.
To make this work, you must ensure your target element has a unique id
.
1<h2 id="heading2">Heading</h2>
And then, create a link whose href
attribute points to the previously defined id
. Make sure you are using the id
selector, #
.
1<a href="#heading2">Go</a>
Link title
Optionally, you can specify a link title, which will be displayed as a tooltip text when the cursor is hovered over.
Open demo in new tab