Absolute Links, Relative Links, and ID Links

Absolute Links, Relative Links, and ID Links
namecheap placeholder image

Links, or hyperlinks, on the web are the primary form of navigation. Without them, the web as we know it would be a very different place.

Absolute Links

Absolute links are links that are given an exact destination. Creating an absolute link can be done with an anchor tag, or a tag. These tags require a destination which is basically where you want the user to go to upon clicking it.

Giving your anchor tag a destination is done by giving a value to the href attribute.

	
	<!DOCTYPE html>
	<html>
		<head>
			<title>Absolute Links</title>
		</head>
		<body>
			<h1>Search the web!</h1>
			<p>
				<a href="https://www.google.com">Google</a>
			</p>
		</body>
	</html>
	
This is how a link looks like.
This is how a link looks like.

In our case, since we provided a direct link to Google's homepage, that is where clicking the link will take us.

Relative Links

Absolute links are cool, but what if you just want to link to a file in the same page/directory/folder? This is where relative links come into play.

For example, if you have two files in the same directory/folder, index.html and food.html, you can link from index.html to food.html by doing something like this:

	
	<a href="food.html">This is a link to food.html!</a>
	

If you want your relative link to be relative to the root instead of the current, folder/directory, start the link off with a /.

Also important to know, if you want to make your links open a new tab, give it a target attribute with the value of _blank, like so:

	
	<a href="food.html" target="_blank">This link will open in a new tab.</a>
	

ID Links

Another popular use of the anchor tag is giving the href attribute a value of an id of another element on the page.

Clicking on this link will make your browser scroll to that element on the page. This is useful for skipping large sections of your page.

Here's an example:

	
	<!DOCTYPE html>
	<html>
		<head>
			<title>ID Link</title>
		</head>
		<body>
			<p>
				<a href="#cereal">Click here to scroll to a good cereal.</a>
			</p>
			<p id="cereal">Corn Flakes</p>
		</body>
	</html>
	
If you make your browser window small enough vertically, you will see that it does work.
If you make your browser window small enough vertically, you will see that it does work.

In our next lesson, make your page pretty by adding images and SVG graphics to them!