Consent

This site uses third party services that need your consent.

Skip to content
Steven Roland
  • Base Element: Setting the Base URL for Relative Links

    The <base> HTML element is used to specify a base URL for all relative URLs within a document. This element is placed within the <head> section and affects how relative URLs are resolved throughout the document, making it easier to manage and maintain links, images, scripts, and other resources. By setting a single base URL, developers can avoid repeating the same URL prefix for every relative link, simplifying the HTML code and reducing potential errors. The <base> element must have either an href attribute, a target attribute, or both, and only one <base> element is allowed per document.

    The href attribute of the <base> element specifies the base URL, which can be either an absolute or relative URL. When a relative URL is used elsewhere in the document, it is resolved against this base URL. The target attribute defines the default browsing context for hyperlinks and forms, determining where the linked resource will open. Common values for the target attribute include _self (current window), _blank (new window or tab), _parent (parent frame), and _top (topmost frame).

    Example Usage

    <!DOCTYPE html>
    <html>
    <head>
      <title>Example of the <base> Element</title>
      <base href="https://www.example.com/" target="_blank">
    </head>
    <body>
      <p>Visit the <a href="about.html">About Us</a> page.</p>
    </body>
    </html>

    In this example, the link to "About Us" will resolve to https://www.example.com/about.html and open in a new tab due to the target="_blank" setting.

    Valid Attributes for <base>

    Attribute Description
    href Specifies the base URL for resolving relative URLs.
    target Sets the default target for hyperlinks and forms (e.g., _blank, _self).

    The <base> element is particularly useful in documents with multiple links or resources that share a common base URL, enhancing code maintainability and consistency. However, it is important to use it carefully, as it affects all relative URLs in the document, and incorrect settings can lead to unexpected results.