Problem Statement
Explain the difference between absolute and relative URLs with examples.
Explanation
Absolute and relative URLs are two different ways to specify link destinations in HTML. Understanding the difference is crucial for web development. An absolute URL is a complete web address that includes the protocol such as http or https, the domain name, and the full path to the resource. For example, https colon slash slash www dot example dot com slash about dot html is an absolute URL. It contains everything needed to locate the resource from anywhere on the internet. Absolute URLs are used when linking to external websites or when you need a link that works regardless of the current page location. They never change based on where you use them. A relative URL is a path relative to the current page or website. It does not include the protocol or domain name. Relative URLs come in different forms. A page-relative URL like about dot html looks for the file in the same directory as the current page. A parent-relative URL like dot dot slash contact dot html looks in the parent directory. A root-relative URL like slash images slash logo dot png starts from the website root. Relative URLs are shorter and more flexible for internal website links. If you change your domain name, relative URLs still work without modification. However, if you move pages to different directories, page-relative URLs may break. Best practices include using absolute URLs for external links to other websites and relative URLs for internal links within your own website. For internal links, root-relative URLs starting with a slash are often preferred because they work consistently across your entire site. Understanding when to use each type is important for maintainable websites and is commonly asked in interviews.
Code Solution
SolutionRead Only
<!-- ABSOLUTE URLs (full address) --> <a href="https://www.google.com">Google</a> <a href="https://example.com/about.html">About</a> <a href="http://website.org/page.html">External</a> <!-- RELATIVE URLs --> <!-- Page-relative (same directory) --> <a href="contact.html">Contact</a> <a href="page2.html">Page 2</a> <!-- Parent directory --> <a href="../index.html">Home</a> <a href="../../main.html">Main</a> <!-- Root-relative (from website root) --> <a href="/about.html">About</a> <a href="/images/logo.png">Logo</a> <a href="/products/item.html">Product</a> <!-- Subdirectory --> <a href="images/photo.jpg">Photo</a> <a href="docs/guide.pdf">Guide</a>
