Html
Structuring the web with HTML
To build websites, you should know about HTML — the fundamental technology used to define the structure of a webpage. HTML is used to specify whether your web content should be recognized as a paragraph, list, heading, link, image, multimedia player, form, or one of many other available elements or even a new element that you define.
Looking to become a front-end web developer?
We have put together a course that includes all the essential information you need to work towards your goal.
Before starting this topic, you should have at least basic familiarity with using computers and using the web passively (i.e. just looking at it, consuming the content). You should have a basic work environment set up as detailed in Installing basic software, and understand how to create and manage files, as detailed in Dealing with files — both are parts of our Getting started with the web complete beginner's module.
It is recommended that you work through Getting started with the web before attempting this topic. However, this isn't absolutely necessary; much of what is covered in the HTML basics article is also covered in our Introduction to HTML module, albeit in a lot more detail.
After learning HTML, you can then move on to learning about more advanced topics such as:
CSS, and how to use it to style HTML (for example alter your text size and fonts used, add borders and drop shadows, layout your page with multiple columns, add animations and other visual effects.)
JavaScript, and how to use it to add dynamic functionality to web pages (for example find your location and plot it on a map, make UI elements appear/disappear when you toggle a button, save users' data locally on their computers, and much more.)
This topic contains the following modules, in a suggested order for working through them. You should definitely start with the first one.
This module sets the stage, getting you used to important concepts and syntax, looking at applying HTML to text, how to create hyperlinks, and how to use HTML to structure a webpage.
This module explores how to use HTML to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire other webpages.
Representing tabular data on a webpage in an understandable, accessible way can be a challenge. This module covers basic table markup, along with more complex features such as implementing captions and summaries.
Use HTML to solve common problems provides links to sections of content explaining how to use HTML to solve very common problems when creating a webpage: dealing with titles, adding images or videos, emphasizing content, creating a basic form, etc.
This module provides a series of articles that will help you master the essentials of web forms. Web forms are a very powerful tool for interacting with users — most commonly they are used for collecting data from users, or allowing them to control a user interface. However, for historical and technical reasons it's not always obvious how to use them to their full potential. We'll cover all the essential aspects of Web forms including marking up their HTML structure, styling form controls, validating form data, and submitting data to the server.
HTML (HyperText Markup Language)
The main entry point for HTML reference documentation on MDN, including detailed element and attribute references — if you want to know what attributes an element has or what values an attribute has, for example, this is a great place to start.
\
What’s in the head? Metadata in HTML
The head of an HTML document is the part that is not displayed in the web browser when the page is loaded. It contains information such as the page <title>
, links to CSS (if you choose to style your HTML content with CSS), links to custom favicons, and other metadata (data about the HTML, such as the author, and important keywords that describe the document.) In this article we'll cover all of the above and more, in order to give you a good basis for working with markup.
Prerequisites:
Basic HTML familiarity, as covered in Getting started with HTML.
Objective:
To learn about the HTML head, its purpose, the most important items it can contain, and what effect it can have on the HTML document.
Let's revisit the simple HTML document we covered in the previous article:
Copy to Clipboard
The HTML head is the contents of the <head>
element — unlike the contents of the <body>
element (which are displayed on the page when loaded in a browser), the head's content is not displayed on the page. Instead, the head's job is to contain metadata about the document. In the above example, the head is quite small:
Copy to Clipboard
In larger pages however, the head can get quite full. Try going to some of your favorite websites and use the developer tools to check out their head contents. Our aim here is not to show you how to use everything that can possibly be put in the head, but rather to teach you how to use the major elements that you'll want to include in the head, and give you some familiarity. Let's get started.
We've already seen the <title>
element in action — this can be used to add a title to the document. This however can get confused with the <h1>
element, which is used to add a top level heading to your body content — this is also sometimes referred to as the page title. But they are different things!
The
<h1>
element appears on the page when loaded in the browser — generally this should be used once per page, to mark up the title of your page content (the story title, or news headline, or whatever is appropriate to your usage.)The
<title>
element is metadata that represents the title of the overall HTML document (not the document's content.)
To start off this active learning, we'd like you to go to our GitHub repo and download a copy of our title-example.html page. To do this, either
Copy and paste the code out of the page and into a new text file in your code editor, then save it in a sensible place.
Press the "Raw" button on the GitHub page, which causes the raw code to appear (possibly in a new browser tab). Next, choose your browser's File > Save Page As... menu and choose a sensible place to save the file.
You should also try opening the code up in your code editor, editing the contents of these elements, then refreshing the page in your browser. Have some fun with it.
The <title>
element contents are also used in other ways. For example, if you try bookmarking the page (Bookmarks > Bookmark This Page or the star icon in the URL bar in Firefox), you will see the <title>
contents filled in as the suggested bookmark name.
The <title>
contents are also used in search results, as you'll see below.
Metadata is data that describes data, and HTML has an "official" way of adding metadata to a document — the <meta>
element. Of course, the other stuff we are talking about in this article could also be thought of as metadata too. There are a lot of different types of <meta>
elements that can be included in your page's <head>, but we won't try to explain them all at this stage, as it would just get too confusing. Instead, we'll explain a few things that you might commonly see, just to give you an idea.
In the example we saw above, this line was included:
Copy to Clipboard
This element specifies the document's character encoding — the character set that the document is permitted to use. utf-8
is a universal character set that includes pretty much any character from any human language. This means that your web page will be able to handle displaying any language; it's therefore a good idea to set this on every web page you create! For example, your page could handle English and Japanese just fine:
Note: Some browsers (like Chrome) automatically fix incorrect encodings, so depending on what browser you use, you may not see this problem. You should still set an encoding of utf-8
on your page anyway to avoid any potential problems in other browsers.
To try this out, revisit the simple HTML template you obtained in the previous section on <title>
(the title-example.html page), try changing the meta charset value to ISO-8859-1
, and add the Japanese to your page. This is the code we used:
Copy to Clipboard
Many <meta>
elements include name
and content
attributes:
name
specifies the type of meta element it is; what type of information it contains.content
specifies the actual meta content.
Two such meta elements that are useful to include on your page define the author of the page, and provide a concise description of the page. Let's look at an example:
Copy to Clipboard
Specifying an author is beneficial in many ways: it is useful to be able to understand who wrote the page, if you have any questions about the content and you would like to contact them. Some content management systems have facilities to automatically extract page author information and make it available for such purposes.
Specifying a description that includes keywords relating to the content of your page is useful as it has the potential to make your page appear higher in relevant searches performed in search engines (such activities are termed Search Engine Optimization, or SEO.)
The description is also used on search engine result pages. Let's go through an exercise to explore this
Go to the front page of The Mozilla Developer Network.
View the page's source (right-click on the page, choose View Page Source from the context menu.)
Find the description meta tag. It will look something like this (although it may change over time):
Copy to Clipboard
Note: In Google, you will see some relevant subpages of MDN Web Docs listed below the main homepage link — these are called sitelinks, and are configurable in Google's webmaster tools — a way to make your site's search results better in the Google search engine.
Note: Many <meta>
features just aren't used any more. For example, the keyword <meta>
element (<meta name="keywords" content="fill, in, your, keywords, here">
) — which is supposed to provide keywords for search engines to determine relevance of that page for different search terms — is ignored by search engines, because spammers were just filling the keyword list with hundreds of keywords, biasing results.
As you travel around the web, you'll find other types of metadata, too. A lot of the features you'll see on websites are proprietary creations, designed to provide certain sites (such as social networking sites) with specific pieces of information they can use.
For example, Open Graph Data is a metadata protocol that Facebook invented to provide richer metadata for websites. In the MDN Web Docs sourcecode, you'll find this:
Copy to Clipboard
One effect of this is that when you link to MDN Web Docs on facebook, the link appears along with an image and description: a richer experience for users.
Twitter also has its own similar proprietary metadata called Twitter Cards, which has a similar effect when the site's URL is displayed on twitter.com. For example:
Copy to Clipboard
To further enrich your site design, you can add references to custom icons in your metadata, and these will be displayed in certain contexts. The most commonly used of these is the favicon (short for "favorites icon", referring to its use in the "favorites" or "bookmarks" lists in browsers).
The humble favicon has been around for many years. It is the first icon of this type: a 16-pixel square icon used in multiple places. You may see (depending on the browser) favicons displayed in the browser tab containing each open page, and next to bookmarked pages in the bookmarks panel.
A favicon can be added to your page by:
Saving it in the same directory as the site's index page, saved in
.ico
format (most browsers will support favicons in more common formats like.gif
or.png
, but using the ICO format will ensure it works as far back as Internet Explorer 6.)
Here is an example of a favicon in a bookmarks panel:
There are lots of other icon types to consider these days as well. For example, you'll find this in the source code of the MDN Web Docs homepage:
Copy to Clipboard
The comments explain what each icon is used for — these elements cover things like providing a nice high resolution icon to use when the website is saved to an iPad's home screen.
Don't worry too much about implementing all these types of icon right now — this is a fairly advanced feature, and you won't be expected to have knowledge of this to progress through the course. The main purpose here is to let you know what such things are, in case you come across them while browsing other websites' source code.
Note: If your site uses a Content Security Policy (CSP) to enhance its security, the policy applies to the favicon. If you encounter problems with the favicon not loading, verify that the Content-Security-Policy
header's img-src
directive is not preventing access to it.
Just about all websites you'll use in the modern day will employ CSS to make them look cool, and JavaScript to power interactive functionality, such as video players, maps, games, and more. These are most commonly applied to a web page using the <link>
element and the <script>
element, respectively.
The
<link>
element should always go inside the head of your document. This takes two attributes,rel="stylesheet"
, which indicates that it is the document's stylesheet, andhref
, which contains the path to the stylesheet file:Copy to Clipboard
The
<script>
element should also go into the head, and should include asrc
attribute containing the path to the JavaScript you want to load, anddefer
, which basically instructs the browser to load the JavaScript after the page has finished parsing the HTML. This is useful as it makes sure that the HTML is all loaded before the JavaScript runs, so that you don't get errors resulting from JavaScript trying to access an HTML element that doesn't exist on the page yet. There are actually a number of ways to handle loading JavaScript on your page, but this is the most foolproof one to use for modern browsers (for others, read Script loading strategies).Copy to Clipboard
Note: The
<script>
element may look like an empty element, but it's not, and so needs a closing tag. Instead of pointing to an external script file, you can also choose to put your script inside the<script>
element.
To start this active learning, grab a copy of our meta-example.html, script.js and style.css files, and save them on your local computer in the same directory. Make sure they are saved with the correct names and file extensions.
Open the HTML file in both your browser, and your text editor.
If done correctly, when you save your HTML and refresh your browser you should be able to see that things have changed:
The JavaScript has added an empty list to the page. Now when you click anywhere outside the list, a dialog box will pop up asking you to enter some text for a new list item. When you press the OK button, a new list item will be added to the list containing the text. When you click on an existing list item, a dialog box will pop up allowing you to change the item's text.
The CSS has caused the background to go green, and the text to become bigger. It has also styled some of the content that the JavaScript has added to the page (the red bar with the black border is the styling the CSS has added to the JS-generated list.)
Note: If you get stuck in this exercise and can't get the CSS/JS to apply, try checking out our css-and-js.html example page.
Finally, it's worth mentioning that you can (and really should) set the language of your page. This can be done by adding the lang attribute to the opening HTML tag (as seen in the meta-example.html and shown below.)
Copy to Clipboard
This is useful in many ways. Your HTML document will be indexed more effectively by search engines if its language is set (allowing it to appear correctly in language-specific results, for example), and it is useful to people with visual impairments using screen readers (for example, the word "six" exists in both French and English, but is pronounced differently.)
You can also set subsections of your document to be recognized as different languages. For example, we could set our Japanese language section to be recognized as Japanese, like so:
Copy to Clipboard
These codes are defined by the ISO 639-1 standard. You can find more about them in Language tags in HTML and XML.
That marks the end of our quickfire tour of the HTML head — there's a lot more you can do in here, but an exhaustive tour would be boring and confusing at this stage, and we just wanted to give you an idea of the most common things you'll find in there for now! In the next article we'll be looking at HTML text
One of HTML's main jobs is to give text structure so that a browser can display an HTML document the way its developer intends. This article explains the way HTML can be used to structure a page of text by adding headings and paragraphs, emphasizing words, creating lists, and more.
Prerequisites:
Basic HTML familiarity, as covered in Getting started with HTML.
Objective:
Learn how to mark up a basic page of text to give it structure and meaning—including paragraphs, headings, lists, emphasis, and quotations.
Most structured text consists of headings and paragraphs, whether you are reading a story, a newspaper, a college textbook, a magazine, etc.
Structured content makes the reading experience easier and more enjoyable.
In HTML, each paragraph has to be wrapped in a <p>
element, like so:
Copy to Clipboard
Each heading has to be wrapped in a heading element:
Copy to Clipboard
There are six heading elements: <h1>
, <h2>
, <h3>
, <h4>
, <h5>
, and <h6>
. Each element represents a different level of content in the document; <h1>
represents the main heading, <h2>
represents subheadings, <h3>
represents sub-subheadings, and so on.
For example, in this story, the <h1>
element represents the title of the story, the <h2>
elements represent the title of each chapter, and the <h3>
elements represent sub-sections of each chapter:
Copy to Clipboard
It's really up to you what the elements involved represent, as long as the hierarchy makes sense. You just need to bear in mind a few best practices as you create such structures:
Preferably, you should use a single
<h1>
per page—this is the top level heading, and all others sit below this in the hierarchy.Make sure you use the headings in the correct order in the hierarchy. Don't use
<h3>
elements to represent subheadings, followed by<h2>
elements to represent sub-subheadings—that doesn't make sense and will lead to weird results.Of the six heading levels available, you should aim to use no more than three per page, unless you feel it is necessary. Documents with many levels (for example, a deep heading hierarchy) become unwieldy and difficult to navigate. On such occasions, it is advisable to spread the content over multiple pages if possible.
To answer this question, let's take a look at text-start.html—the starting point of our running example for this article (a nice hummus recipe). You should save a copy of this file on your local machine, as you'll need it for the exercises later on. This document's body currently contains multiple pieces of content. They aren't marked up in any way, but they are separated with linebreaks (Enter/Return pressed to go onto the next line).
However, when you open the document in your browser, you'll see that the text appears as a big chunk!
This is because there are no elements to give the content structure, so the browser does not know what is a heading and what is a paragraph. Furthermore:
Users looking at a web page tend to scan quickly to find relevant content, often just reading the headings, to begin with. (We usually spend a very short time on a web page.) If they can't see anything useful within a few seconds, they'll likely get frustrated and go somewhere else.
Search engines indexing your page consider the contents of headings as important keywords for influencing the page's search rankings. Without headings, your page will perform poorly in terms of SEO (Search Engine Optimization).
Severely visually impaired people often don't read web pages; they listen to them instead. This is done with software called a screen reader. This software provides ways to get fast access to given text content. Among the various techniques used, they provide an outline of the document by reading out the headings, allowing their users to find the information they need quickly. If headings are not available, they will be forced to listen to the whole document read out loud.
To style content with CSS, or make it do interesting things with JavaScript, you need to have elements wrapping the relevant content, so CSS/JavaScript can effectively target it.
Therefore, we need to give our content structural markup.
Let's jump straight in with a live example. In the example below, add elements to the raw text in the Input field so that it appears as a heading and two paragraphs in the Output field.
If you make a mistake, you can always reset it using the Reset button. If you get stuck, press the Show solution button to see the answer.
Semantics are relied on everywhere around us—we rely on previous experience to tell us what the function of an everyday object is; when we see something, we know what its function will be. So, for example, we expect a red traffic light to mean "stop," and a green traffic light to mean "go." Things can get tricky very quickly if the wrong semantics are applied. (Do any countries use red to mean "go"? We hope not.)
In a similar vein, we need to make sure we are using the correct elements, giving our content the correct meaning, function, or appearance. In this context, the <h1>
element is also a semantic element, which gives the text it wraps around the role (or meaning) of "a top level heading on your page."
Copy to Clipboard
By default, the browser will give it a large font size to make it look like a heading (although you could style it to look like anything you wanted using CSS). More importantly, its semantic value will be used in multiple ways, for example by search engines and screen readers (as mentioned above).
On the other hand, you could make any element look like a top level heading. Consider the following:
Copy to Clipboard
This is a <span>
element. It has no semantics. You use it to wrap content when you want to apply CSS to it (or do something to it with JavaScript) without giving it any extra meaning. (You'll find out more about these later on in the course.) We've applied some CSS to it to make it look like a top level heading, but since it has no semantic value, it will not get any of the extra benefits described above. It is a good idea to use the relevant HTML element for the job.
Now let's turn our attention to lists. Lists are everywhere in life—from your shopping list to the list of directions you subconsciously follow to get to your house every day, to the lists of instructions you are following in these tutorials! Lists are everywhere on the web, too, and we've got three different types to worry about.
Unordered lists are used to mark up lists of items for which the order of the items doesn't matter. Let's take a shopping list as an example:
Every unordered list starts off with a <ul>
element—this wraps around all the list items:
Copy to Clipboard
The last step is to wrap each list item in a <li>
(list item) element:
Copy to Clipboard
Active learning: Marking up an unordered list
Try editing the live sample below to create your very own HTML unordered list.
Ordered lists are lists in which the order of the items does matter. Let's take a set of directions as an example:
The markup structure is the same as for unordered lists, except that you have to wrap the list items in an <ol>
element, rather than <ul>
:
Copy to Clipboard
Active learning: Marking up an ordered list
Try editing the live sample below to create your very own HTML ordered list.
So at this point in the article, you have all the information you need to mark up our recipe page example. You can choose to either save a local copy of our text-start.html starting file and do the work there or do it in the editable example below. Doing it locally will probably be better, as then you'll get to save the work you are doing, whereas if you fill it in to the editable example, it will be lost the next time you open the page. Both have pros and cons.
If you get stuck, you can always press the Show solution button, or check out our text-complete.html example on our github repo.
It is perfectly OK to nest one list inside another one. You might want to have some sub-bullets sitting below a top-level bullet. Let's take the second list from our recipe example:
Copy to Clipboard
Since the last two bullets are very closely related to the one before them (they read like sub-instructions or choices that fit below that bullet), it might make sense to nest them inside their own unordered list and put that list inside the current fourth bullet. This would look like so:
Copy to Clipboard
Try going back to the previous active learning example and updating the second list like this.
In human language, we often emphasize certain words to alter the meaning of a sentence, and we often want to mark certain words as important or different in some way. HTML provides various semantic elements to allow us to mark up textual content with such effects, and in this section, we'll look at a few of the most common ones.
When we want to add emphasis in spoken language, we stress certain words, subtly altering the meaning of what we are saying. Similarly, in written language we tend to stress words by putting them in italics. For example, the following two sentences have different meanings.
I am glad you weren't late.
I am glad you weren't late.
The first sentence sounds genuinely relieved that the person wasn't late. In contrast, the second one sounds sarcastic or passive-aggressive, expressing annoyance that the person arrived a bit late.
In HTML we use the <em>
(emphasis) element to mark up such instances. As well as making the document more interesting to read, these are recognized by screen readers and spoken out in a different tone of voice. Browsers style this as italic by default, but you shouldn't use this tag purely to get italic styling. To do that, you'd use a <span>
element and some CSS, or perhaps an <i>
element (see below).
Copy to Clipboard
To emphasize important words, we tend to stress them in spoken language and bold them in written language. For example:
This liquid is highly toxic.
I am counting on you. Do not be late!
In HTML we use the <strong>
(strong importance) element to mark up such instances. As well as making the document more useful, again these are recognized by screen readers and spoken in a different tone of voice. Browsers style this as bold text by default, but you shouldn't use this tag purely to get bold styling. To do that, you'd use a <span>
element and some CSS, or perhaps a <b>
element (see below).
Copy to Clipboard
You can nest strong and emphasis inside one another if desired:
Copy to Clipboard
In this active learning section, we've provided an editable example. Inside it, we'd like you to try adding emphasis and strong importance to the words you think need them, just to have some practice.
The elements we've discussed so far have clearcut associated semantics. The situation with <b>
, <i>
, and <u>
is somewhat more complicated. They came about so people could write bold, italics, or underlined text in an era when CSS was still supported poorly or not at all. Elements like this, which only affect presentation and not semantics, are known as presentational elements and should no longer be used because, as we've seen before, semantics is so important to accessibility, SEO, etc.
HTML5 redefined <b>
, <i>
, and <u>
with new, somewhat confusing, semantic roles.
Here's the best rule of thumb: It's likely appropriate to use <b>
, <i>
, or <u>
to convey a meaning traditionally conveyed with bold, italics, or underline, provided there is no more suitable element. However, it always remains critical to keep an accessibility mindset. The concept of italics isn't very helpful to people using screen readers, or to people using a writing system other than the Latin alphabet.
<i>
is used to convey a meaning traditionally conveyed by italic: foreign words, taxonomic designation, technical terms, a thought...<b>
is used to convey a meaning traditionally conveyed by bold: key words, product names, lead sentence...<u>
is used to convey a meaning traditionally conveyed by underline: proper name, misspelling...
Note: People strongly associate underlining with hyperlinks. Therefore, on the web, it's best to underline only links. Use the <u>
element when it's semantically appropriate, but consider using CSS to change the default underline to something more appropriate on the web. The example below illustrates how it can be done.
Copy to Clipboard
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on—see Test your skills: HTML text basics.
That's it for now! This article should have given you a good idea of how to start marking up text in HTML and introduced you to some of the most important elements in this area. There are a lot more semantic elements to cover in this area, and we'll look at a lot more in our Advanced text formatting article later on in the course. In the next article, we'll be looking in detail at how to create hyperlinks, possibly the most important element on the web.Hyperlinks are really important — they are what makes the Web a web. This article shows the syntax required to make a link, and discusses link best practices.
Prerequisites:
Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:
To learn how to implement a hyperlink effectively, and link multiple files together.
Hyperlinks are one of the most exciting innovations the Web has to offer. They've been a feature of the Web since the beginning, and are what makes the Web a web. Hyperlinks allow us to link documents to other documents or resources, link to specific parts of documents, or make apps available at a web address. Almost any web content can be converted to a link so that when clicked or otherwise activated the web browser goes to another web address (URL).
Note: A URL can point to HTML files, text files, images, text documents, video and audio files, or anything else that lives on the Web. If the web browser doesn't know how to display or handle the file, it will ask you if you want to open the file (in which case the duty of opening or handling the file is passed to a suitable native app on the device) or download the file (in which case you can try to deal with it later on).
For example, the BBC homepage contains many links that point not only to multiple news stories, but also different areas of the site (navigation functionality), login/registration pages (user tools), and more.
A basic link is created by wrapping the text or other content, see Block level links, inside an <a>
element and using the href
attribute, also known as a Hypertext Reference, or target, that contains the web address.
Copy to Clipboard
This gives us the following result:
I'm creating a link to the Mozilla homepage.
Another attribute you may want to add to your links is title
. The title contains additional information about the link, such as which kind of information the page contains, or things to be aware of on the web site.
Copy to Clipboard
This gives us the following result and hovering over the link displays the title as a tooltip:
I'm creating a link to the Mozilla homepage.
Note: A link title is only revealed on mouse hover, which means that people relying on keyboard controls or touchscreens to navigate web pages will have difficulty accessing title information. If a title's information is truly important to the usability of the page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.
Create an HTML document using your local code editor and our getting started template.
Inside the HTML body, add one or more paragraphs or other types of content you already know about.
Change some of the content into links.
Include title attributes.
As mentioned before, almost any content can be made into a link, even block-level elements. If you have an image you want to make into a link, use the <a>
element and reference the image file with the <img>
element.
Copy to Clipboard
Note: You'll find out more about using images on the Web in a future article.
To fully understand link targets, you need to understand URLs and file paths. This section gives you the information you need to achieve this.
A URL, or Uniform Resource Locator is a string of text that defines where something is located on the Web. For example, Mozilla's English homepage is located at https://www.mozilla.org/en-US/
.
URLs use paths to find files. Paths specify where the file you're interested in is located in the filesystem. Let's look at an example of a directory structure, see the creating-hyperlinks directory.
The root of this directory structure is called creating-hyperlinks
. When working locally with a web site, you'll have one directory that contains the entire site. Inside the root, we have an index.html
file and a contacts.html
. In a real website, index.html
would be our home page or landing page (a web page that serves as the entry point for a website or a particular section of a website.).
There are also two directories inside our root — pdfs
and projects
. These each have a single file inside them — a PDF (project-brief.pdf
) and an index.html
file, respectively. Note that you can have two index.html
files in one project, as long as they're in different filesystem locations. The second index.html
would perhaps be the main landing page for project-related information.
Same directory: If you wanted to include a hyperlink inside
index.html
(the top levelindex.html
) pointing tocontacts.html
, you would specify the filename that you want to link to, because it's in the same directory as the current file. The URL you would use iscontacts.html
:Copy to Clipboard
Moving down into subdirectories: If you wanted to include a hyperlink inside
index.html
(the top levelindex.html
) pointing toprojects/index.html
, you would need to go down into theprojects
directory before indicating the file you want to link to. This is done by specifying the directory's name, then a forward slash, then the name of the file. The URL you would use isprojects/index.html
:Copy to Clipboard
Moving back up into parent directories: If you wanted to include a hyperlink inside
projects/index.html
pointing topdfs/project-brief.pdf
, you'd have to go up a directory level, then back down into thepdf
directory. To go up a directory, use two dots —..
— so the URL you would use is../pdfs/project-brief.pdf
:Copy to Clipboard
Note: You can combine multiple instances of these features into complex URLs, if needed, for example: ../../../complex/path/to/my/file.html
.
It's possible to link to a specific part of an HTML document, known as a document fragment, rather than just to the top of the document. To do this you first have to assign an id
attribute to the element you want to link to. It normally makes sense to link to a specific heading, so this would look something like the following:
Copy to Clipboard
Then to link to that specific id
, you'd include it at the end of the URL, preceded by a hash/pound symbol (#
), for example:
Copy to Clipboard
You can even use the document fragment reference on its own to link to another part of the current document:
Copy to Clipboard
Two terms you'll come across on the Web are absolute URL and relative URL:
absolute URL: Points to a location defined by its absolute location on the web, including protocol and domain name. For example, if an index.html
page is uploaded to a directory called projects
that sits inside the root of a web server, and the web site's domain is https://www.example.com
, the page would be available at https://www.example.com/projects/index.html
(or even just https://www.example.com/projects/
, as most web servers just look for a landing page such as index.html
to load if it isn't specified in the URL.)
An absolute URL will always point to the same location, no matter where it's used.
relative URL: Points to a location that is relative to the file you are linking from, more like what we looked at in the previous section. For example, if we wanted to link from our example file at https://www.example.com/projects/index.html
to a PDF file in the same directory, the URL would just be the filename — project-brief.pdf
— no extra information needed. If the PDF was available in a subdirectory inside projects
called pdfs
, the relative link would be pdfs/project-brief.pdf
(the equivalent absolute URL would be https://www.example.com/projects/pdfs/project-brief.pdf
.)
A relative URL will point to different places depending on the actual location of the file you refer from — for example if we moved our index.html
file out of the projects
directory and into the root of the web site (the top level, not in any directories), the pdfs/project-brief.pdf
relative URL link inside it would now point to a file located at https://www.example.com/pdfs/project-brief.pdf
, not a file located at https://www.example.com/projects/pdfs/project-brief.pdf
.
Of course, the location of the project-brief.pdf
file and pdfs
folder won't suddenly change because you moved the index.html
file — this would make your link point to the wrong place, so it wouldn't work if clicked on. You need to be careful!
There are some best practices to follow when writing links. Let's look at these now.
It's easy to throw links up on your page. That's not enough. We need to make our links accessible to all readers, regardless of their current context and which tools they prefer. For example:
Screenreader users like jumping around from link to link on the page, and reading links out of context.
Search engines use link text to index target files, so it is a good idea to include keywords in your link text to effectively describe what is being linked to.
Visual readers skim over the page rather than reading every word, and their eyes will be drawn to page features that stand out, like links. They will find descriptive link text useful.
Let's look at a specific example:
Good link text: Download Firefox
Copy to Clipboard
Bad link text: Click here to download Firefox
Copy to Clipboard
Other tips:
Don't repeat the URL as part of the link text — URLs look ugly, and sound even uglier when a screen reader reads them out letter by letter.
Don't say "link" or "links to" in the link text — it's just noise. Screen readers tell people there's a link. Visual users will also know there's a link, because links are generally styled in a different color and underlined (this convention generally shouldn't be broken, as users are used to it).
Keep your link text as short as possible — this is helpful because screen readers need to interpret the entire link text.
Minimize instances where multiple copies of the same text are linked to different places. This can cause problems for screen reader users, if there's a list of links out of context that are labeled "click here", "click here", "click here".
When linking to a resource that will be downloaded (like a PDF or Word document), streamed (like video or audio), or has another potentially unexpected effect (opens a popup window, or loads a Flash movie), you should add clear wording to reduce any confusion.
For example:
If you're on a low bandwidth connection, click a link, and then a multiple megabyte download starts unexpectedly.
If you don't have the Flash player installed, click a link, and then suddenly get taken to a page that requires Flash.
Let's look at some examples, to see what kind of text can be used here:
Copy to Clipboard
When you are linking to a resource that's to be downloaded rather than opened in the browser, you can use the download
attribute to provide a default save filename. Here's an example with a download link to the latest Windows version of Firefox:
Copy to Clipboard
For this exercise, we'd like you to link some pages together with a navigation menu to create a multi-page website. This is one common way in which a website is created — the same page structure is used on every page, including the same navigation menu, so when links are clicked it gives the impression that you are staying in the same place, and different content is being brought up.
You'll need to make local copies of the following four pages, all in the same directory. For a complete file list, see the navigation-menu-start directory:
You should:
Add an unordered list in the indicated place on one page that includes the names of the pages to link to. A navigation menu is usually just a list of links, so this is semantically OK.
Change each page name into a link to that page.
Copy the navigation menu across to each page.
On each page, remove just the link to that same page — it's confusing and unnecessary for a page to include a link to itself. And, the lack of a link acts a good visual reminder of which page you are currently on.
The finished example should look similar to the following page:
Note: If you get stuck, or aren't sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer.
It's possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. This is done using the <a>
element and the mailto:
URL scheme.
In its most basic and commonly used form, a mailto:
link indicates the email address of the intended recipient. For example:
Copy to Clipboard
This results in a link that looks like this: Send email to nowhere.
In fact, the email address is optional. If you omit it and your href
is "mailto:", a new outgoing email window will be opened by the user's email client with no destination address. This is often useful as "Share" links that users can click to send an email to an address of their choosing.
In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto
URL you provide. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term.
Here's an example that includes a cc, bcc, subject and body:
Copy to Clipboard
Note: The values of each field must be URL-encoded, that is with non-printing characters (invisible characters like tabs, carriage returns, and page breaks) and spaces percent-escaped. Also, note the use of the question mark (?
) to separate the main URL from the field values, and ampersands (&) to separate each field in the mailto:
URL. This is standard URL query notation. Read The GET method to understand what URL query notation is more commonly used for.
Here are a few other sample mailto
URLs:
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Links.
That's it for links, for now anyway! You'll return to links later on in the course when you start to look at styling them. Next up for HTML, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful — Advanced text formatting is your next stop.
There are many other elements in HTML for formatting text, which we didn't get to in the HTML text fundamentals article. The elements described in this article are less known, but still useful to know about (and this is still not a complete list by any means). Here you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more.
Prerequisites:
Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:
To learn how to use lesser-known HTML elements to mark up advanced semantic features.
In HTML text fundamentals, we walked through how to mark up basic lists in HTML, but we didn't mention the third type of list you'll occasionally come across — description lists. The purpose of these lists is to mark up a set of items and their associated descriptions, such as terms and definitions, or questions and answers. Let's look at an example of a set of terms and definitions:
Description lists use a different wrapper than the other list types — <dl>
; in addition each term is wrapped in a <dt>
(description term) element, and each description is wrapped in a <dd>
(description definition) element.
Let's finish marking up our example:
Copy to Clipboard
The browser default styles will display description lists with the descriptions indented somewhat from the terms.
Note that it is permitted to have a single term with multiple descriptions, for example:
Copy to Clipboard
It's time to try your hand at description lists; add elements to the raw text in the Input field so that it appears as a description list in the Output field. You could try using your own terms and descriptions if you like.
If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.
HTML also has features available for marking up quotations; which element you use depends on whether you are marking up a block or inline quotation.
If a section of block level content (be it a paragraph, multiple paragraphs, a list, etc.) is quoted from somewhere else, you should wrap it inside a <blockquote>
element to signify this, and include a URL pointing to the source of the quote inside a cite
attribute. For example, the following markup is taken from the MDN <blockquote>
element page:
Copy to Clipboard
To turn this into a block quote, we would just do this:
Copy to Clipboard
Browser default styling will render this as an indented paragraph, as an indicator that it is a quote; the paragraph above the quotation is there to demonstrate that.
Inline quotations work in exactly the same way, except that they use the <q>
element. For example, the below bit of markup contains a quotation from the MDN <q>
page:
Copy to Clipboard
Browser default styling will render this as normal text put in quotes to indicate a quotation, like so:
The content of the cite
attribute sounds useful, but unfortunately browsers, screenreaders, etc. don't really do much with it. There is no way to get the browser to display the contents of cite
, without writing your own solution using JavaScript or CSS. If you want to make the source of the quotation available on the page you need to make it available in the text via a link or some other appropriate way.
There is a <cite>
element, but this is meant to contain the title of the resource being quoted, e.g. the name of the book. There is no reason, however, why you couldn't link the text inside <cite>
to the quote source in some way:
Copy to Clipboard
Citations are styled in italic font by default.
Time for another active learning example! In this example we'd like you to:
Turn the middle paragraph into a blockquote, which includes a
cite
attribute.Turn "The Need To Eliminate Negative Self Talk" in the third paragraph into an inline quote, and include a
cite
attribute.Wrap the title of each source in
<cite>
tags and turn each one into a link to that source.
The citation sources you need are:
http://www.brainyquote.com/quotes/authors/c/confucius.html for the Confucius quote
http://example.com/affirmationsforpositivethinking for "The Need To Eliminate Negative Self Talk".
If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.
Another fairly common element you'll meet when looking around the Web is <abbr>
— this is used to wrap around an abbreviation or acronym, and provide a full expansion of the term (included inside a title
attribute.)
Let's look at an example.
Copy to Clipboard
These will come out looking something like this (the expansion will appear in a tooltip when the term is hovered over):
Note: Earlier versions of html also included support for the <acronym>
element, but it was removed from the HTML spec in favor of using <abbr>
to represent both abbreviations and acronyms. <acronym>
should not be used.
For this simple active learning assignment, we'd like you to mark up an abbreviation. You can use our sample below, or replace it with one of your own.
HTML has an element for marking up contact details — <address>
. This wraps around your contact details, for example:
Copy to Clipboard
It could also include more complex markup, and other forms of contact information, for example:
Copy to Clipboard
Note that something like this would also be OK, if the linked page contained the contact information:
Copy to Clipboard
Note: The <address>
element should only be used to provide contact information for the document contained with the nearest <article>
or <body>
element. It would be correct to use it in the footer of a site to include the contact information of the entire site, on inside an article for the contact details of the author, but not to mark up a list of addresses unrelated to the content of that page.
You will occasionally need to use superscript and subscript when marking up items like dates, chemical formulae, and mathematical equations so they have the correct meaning. The <sup>
and <sub>
elements handle this job. For example:
Copy to Clipboard
The output of this code looks like so:
There are a number of elements available for marking up computer code using HTML:
<code>
: For marking up generic pieces of computer code.<pre>
: For retaining whitespace (generally code blocks) — if you use indentation or excess whitespace inside your text, browsers will ignore it and you will not see it on your rendered page. If you wrap the text in<pre></pre>
tags however, your whitespace will be rendered identically to how you see it in your text editor.<var>
: For specifically marking up variable names.<kbd>
: For marking up keyboard (and other types of) input entered into the computer.<samp>
: For marking up the output of a computer program.
Let's look at a few examples. You should try having a play with these (try grabbing a copy of our other-semantics.html sample file):
Copy to Clipboard
The above code will look like so:
HTML also provides the <time>
element for marking up times and dates in a machine-readable format. For example:
Last updated