HTML <base> Base tag
The <base>
tag in HTML is used to specify a base URL for relative URLs in a document. This means that any relative URLs used in the document will be resolved relative to the base URL specified by the <base>
tag. This is particularly useful for ensuring that relative links work consistently throughout a webpage, especially when dealing with complex directory structures.
Syntax:
<base href="https://www.example.com/" target="_blank">
Attributes:
href
: Specifies the base URL for all relative URLs in the document. This is the most commonly used attribute. It defines the root URL that relative paths will be appended to.Example:
<base href="https://www.example.com/" />
If you have a relative link like
<a href="page.html">
, it will be resolved tohttps://www.example.com/page.html
.target
: Specifies the default target for all hyperlinks in the document. This can be useful if you want all links to open in a specific way, such as in a new tab.Values for
target
include:_blank
: Opens the link in a new tab or window._self
: Opens the link in the same frame (default behavior)._parent
: Opens the link in the parent frame._top
: Opens the link in the full window (top frame).
Example:
<base target="_blank" />
With this attribute, all links will open in a new tab or window by default.
Example Usage:
<!DOCTYPE html>
<html>
<head>
<base href="https://www.example.com/" target="_blank">
</head>
<body>
<a href="page1.html">Go to Page 1</a>
<a href="page2.html">Go to Page 2</a>
</body>
</html>
In this example:
- The
<base>
tag setshttps://www.example.com/
as the base URL. - The
<a href="page1.html">
link will point tohttps://www.example.com/page1.html
. - The
target="_blank"
attribute causes both links to open in a new tab or window.
Important Points:
- Single
<base>
Tag: Only one<base>
tag is allowed per HTML document. It must be placed inside the<head>
section. - Overrides Relative URLs: The
<base>
tag affects all relative URLs in the document, including<a>
,<img>
,<form>
, and other elements that use relative paths. - Global Effect: The base URL specified applies to the entire document, so be cautious when using it, as it affects all relative links and resources.
Limitations:
- No Effect on Absolute URLs: Absolute URLs are not affected by the
<base>
tag. For example,<a href="https://www.example2.com/">
will not be altered by the<base>
tag. - Browser Compatibility: The
<base>
tag is well-supported across modern browsers, but its use should be carefully considered, especially for large or complex documents.