HTML <base> Tag

The HTML <base> tag specifies the base URL and/or target for all relative URLs in a document. It is used inside the <head> element and can only appear once in a document.

When you use the <base> tag, all relative links (e.g., images, CSS files, or hyperlinks) in the document will resolve relative to the specified base URL unless they are absolute URLs.

Attributes of HTML <base> Tag

  • href: Specifies the base URL for all relative URLs in the document.
  • target: Specifies the default target for hyperlinks. Common values include:
    • _self: Opens the link in the same window or tab (default).
    • _blank: Opens the link in a new window or tab.
    • _parent: Opens the link in the parent frame.
    • _top: Opens the link in the full body of the window.

Example of HTML <base> Tag

Here is a basic example demonstrating the use of the <base> tag:

index.html

</>
Copy
<!DOCTYPE html>
<html>
    <head>
        <base href="https://example.com/" target="_blank">
        <title>Base Tag Example</title>
    </head>
    <body>
        <h2>Base Tag Example</h2>
        <p>Here are some links:</p>
        <a href="page1.html">Page 1</a><br>
        <a href="page2.html">Page 2</a>
    </body>
</html>
Example of HTML <base> Tag

Explanation: In this example, all relative URLs (e.g., page1.html and page2.html) are resolved based on the base URL https://example.com/. Additionally, all links open in a new tab due to the target="_blank" attribute.

Special Cases for HTML <base> Tag

Using <base> with Images

The <base> tag can also affect the paths to images:

index.html

</>
Copy
<!DOCTYPE html>
<html>
    <head>
        <base href="https://example.com/assets/">
    </head>
    <body>
        <h2>Images with Base Tag</h2>
        <img src="image1.jpg" alt="Image 1">
        <img src="image2.jpg" alt="Image 2">
    </body>
</html>

Explanation: The images image1.jpg and image2.jpg are loaded from the directory https://example.com/assets/ because of the base URL specified in the <base> tag.

Handling Multiple <base> Tags

Only the first <base> tag in the document is used. Any additional <base> tags are ignored.

Example:

</>
Copy
<!DOCTYPE html>
<html>
    <head>
        <base href="https://example1.com/">
        <base href="https://example2.com/"> 
    </head>
    <body>
        <a href="page.html">Visit Page</a>
    </body>
</html>

Result: The link page.html resolves to https://example1.com/page.html.

Combining <base> with Absolute URLs

The <base> tag does not affect absolute URLs. Absolute URLs always use the full specified path, ignoring the base URL.

Example:

</>
Copy
<!DOCTYPE html>
<html>
    <head>
        <base href="https://example.com/">
    </head>
    <body>
        <a href="https://absolute.com/page.html">Visit Absolute Page</a>
    </body>
</html>

Result: The link resolves to https://absolute.com/page.html and not https://example.com/https://absolute.com/page.html.