Why Base Tag Does Not Work for Relative Paths

Why base tag does not work for relative paths?

/assets/jquery-1.7.1.min.js is not relative but absolute*, the / takes it to the root even with a base tag.

If you remove that /, it should make it relative off the current path, which, when a base tag is present would be http://localhost/framework/.

Note: You will also need to add a trailing / to the end of the href, to indicate that it's a folder.

Full working example:

<!doctype html>
<html>
<head>
<base href="/test/" />
<script src="assets/test.js"></script>
<body>
hi
</body>
</html>

* Actually depending on who you ask, it's still relative since it is relative off the current domain. But I prefer to call this absolute since it's signifying the path is from the root, based on the current domain. Although, I guess technically that makes it relative in the grand scheme of things, and absolute only in terms of the current domain. Whatever.

HTML5 base Tag with root relative url

Does <base> tag universally support root relative urls (i.e. href="/bob/")?

Yes, <base> accepts domain-relative (path-absolute) URLs and will correctly resolve them relative to the host name.

<base href="/bob/"> means that you want all path-relative URLs (i.e. URLs that contain just a path but don't start with /) to be relative to /bob/, such that

  • <a href="foo.html"> will point to /bob/foo.html, regardless of the domain.

Domain-absolute and path-absolute links will not be adjusted: respectively,

  • <a href="https://stackoverflow.com"> will still point to https://stackoverflow.com, and
  • <a href="/bar"> will still point to /bar.

As long as this is how you intend for your path-relative links to behave, you're not misusing the <base> element this way. As always, when using the <base> element it's a good idea to test your links from time to time to make sure they're still pointing to the right URLs.

Firefox: Can I use a relative path in the BASE tag?

In HTML4, <base> needs an absolute URI. However, since HTML5 now has widespread support, it should be mentioned that the HTML5 <base> tag accepts an URL, which can be either absolute or relative; this effectively means that you can now use a relative path instead of an absolute URI.

Best way to deal with relative paths/base tag

I ended up using a <base> tag in the header, and then wherever I needed anchor links I used php like so: <a href="http://<?php echo $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];?>#">

This makes the link go to the current page with a # added to the end, so it's the same as using <a href="#">

Let me know if you think I could have done this a better way! Thanks!

Relative path for img agnostic to base tag

Regrettably (or maybe not), there is no way to achieve this in pure HTML. Possible workarounds include either not using a relative path or using JavaScript to generate an absolute path.



Related Topics



Leave a reply



Submit