HTML Cookbook Basic HTML Course

It's Easy!

Directories and URL's, Part 4, the Base tag

We've already learned how to use short URL's relative to the directory that our page is in. Now we'll learn how to use short URL's that are relative to a different directory.

Why would you want to do that?

Let's say you have a page with pictures of your pets. Let's call it "my_pets.html". This page is in your root directory.

Here's your root directory URL:
http://www.myhost.com/myaccount/

Here's the URL of your page:
http://www.myhost.com/myaccount/my_pets.html


Now let's say that you keep all of your images in an images subdirectory:
http://www.myhost.com/myaccount/images/

You have a lot of images, so you keep your pet pictures in a subdirectory called my_pets:
http://www.myhost.com/myaccount/images/my_pets/


Here's part of the directory tree:
Here is some code from my_pets.html.
<img src="images/my_pets/my_canary.jpg" />
<br /><br />
<img src="images/my_pets/my_cat.jpg" />
<br /><br />
<img src="images/my_pets/my_dog.jpg" />
<br /><br />
<img src="images/my_pets/my_goldfish.jpg" />
<br /><br />

Wouldn't it be nice if we could change our working directory to images/my_pets/ ?

We can do just that with the base tag.


The Base tag:

Form: <base href="URL" />

The base tag goes in the head of your page. You may only use one base tag per page. The base tag assigns a directory of your choice to be the working directory for your page.

Concept: All short URL's are relative to the directory that is entered in your base tag.

What does that mean?

Wherever you use a relative URL in your page, browsers will look for files in the directory that is specified in the base tag.

To use the base tag, simply enter the absolute URL of your working directory. In our example, most of the files we are using in our page are in the images/my_pets directory, so we'll use that URL.

<head>
<base href="http://www.myhost.com/myaccount/images/my_pets/" />
</head>

Since our working directory is now images/my_pets, all we need to enter for our image URL's are the file names:

<img src="my_canary.jpg" />
<br /><br />
<img src="my_cat.jpg" />
<br /><br />
<img src="my_dog.jpg" />
<br /><br />
<img src="my_goldfish.jpg" />
<br /><br />

Hey Gnubee, what if I want to use a file from a different directory?

You assign a working directory in the base tag. Now all short URL's must be relative to that working directory.

Example:
Let's say you keep all of your banners in a banners directory and you have a banner for your pet page:
http://www.myhost.com/myaccount/banners/my_pets.gif

Your working directory is images/my_pets/. Go up 2 levels to your root, then go down to your banner:
<img src="../../banners/my_pets.gif>

Happy coding!
Gnubee

Links
Tips
Tools
References
Rules
HTML Help Gnubee - Newsgroup
HTML Course Contents (Home)

Valid XHTML 1.0!

Valid CSS!