Difference between absolute and relative URL in HTML
Serhii Shramko /
3 min read • --- views
I am a Frontend mentor in a MacPaw internship and sometimes my interns get confused 🫠 about how links work in HTML.
So I decided to write a small article about this topic.
Anatomy of a URL
URL - is a string that indicates the address of a document or file on the Internet.
Scheme
The first part of the URL is the scheme, which indicates the protocol that the browser must use to request the resource. The protocol is usually HTTPS or HTTP, but can also be:
- ftp
- gopher
- file
- mailto
- and others
Authority
Authority is the domain and optional port like :80
.
Now you are in shramko.dev
domain.
Path to resource or file
/blog/difference-between-absolute-and-relative-url
This is the path to the HTML file of this article. You can check it in the console if you write:
window.location.pathname
Relative links
These links will always be anchored to the place where they are located. The browser will use the same protocol and the same domain.
Relative to the root of the site
An important point, we add /
to the address at the beginning.
<a href="/about">About page</a>
Relative path from the current document
Similar to the previous example, but the path to the file is saved.
An important point, we do not add /
to the address at the beginning.
<a href="category/js">JS category of Blog</a>
Absolute links
An absolute link is an address to a file or page as a whole, with all the above-described parts of the URL. With such a link, regardless of where this link is located, you will be able to get to the right resource.
You will be taken to any page or site exactly as indicated by a link of this type:
<a href="https://shramko.dev/dashboard">My Dashboard</a>
You can not specify the protocol http/https
, then the browser will automatically use the protocol on which the site
was loaded.
<a href="//shramko.dev/dashboard">My Dashboard</a>
Anchors (links by #id)
Anchor links are usually used to navigate the current page. For example, a link to a paragraph or heading.
The link below moves you to the section about Anatomy of URL on this page.
Add #anatomy-of-a-url
to the current URL in your browser.
Cheat Sheet
Examples that we discussed today.
Useful links
Share it: