HTML. Unit 10. Advanced forms.

How to structure a web form

With the basics out of the way, we’ll now look in more detail at the elements used to provide structure and meaning to the different parts of a form. The flexibility of forms makes them one of the most complex structures in HTML; you can build any kind of basic form using dedicated form elements and attributes. Using correct structure when building an HTML form will help you to ensure that the form is both usable and accessible.

The <form> element

As explained previously, the <form> element formally defines a form and attributes that determine the form’s behaviour. Each time you want to create an HTML form, you must start it by using this element, nesting all the contents inside. Now let’s move forward and cover the structural elements you’ll find nested in a form.

The <fieldset> and <legend> elements

The <fieldset> element is a convenient way to create groups of widgets that share the same purpose, for styling and semantic purposes. You can label a <fieldset> by including a <legend> element just below the opening <fieldset> tag. The text content of the <legend> formally describes the purpose of the <fieldset> it is included inside.

For maximum usability/accessibility, you are advised to surround each list of related items in a <fieldset>, with a <legend> providing an overall description of the list.  Each individual pair of <label>/<input> elements should be contained in its own list item (or similar). The associated <label> is generally placed immediately after the radio button or checkbox, with the instructions for the group of radio button or checkboxes generally being the content of the <legend>. See the examples in the previous unit for structural examples.

Many assistive technologies will use the <legend> element as if it is a part of the label of each control inside the corresponding <fieldset> element. For example, some screen readers such as Jaws and NVDA will speak the legend’s content before speaking the label of each control.

Here is a little example:

<form>
  <fieldset>
    <legend>Fruit juice size</legend>
    <p>
      <label><input type="radio" name="size" value="small" />Small</label>
    </p>
    <p>
      <label><input type="radio" name="size" value="medium" />Medium</label>
    </p>
    <p>
      <label><input type="radio" name="size" value="large" />Large</label>
    </p>
  </fieldset>
</form>
Fruit juice size

When reading the above form, a screen reader will speak “Fruit juice size small” for the first widget, “Fruit juice size medium” for the second, and “Fruit juice size large” for the third.

The use case in this example is one of the most important. Each time you have a set of radio buttons, you should nest them inside a <fieldset> element. There are other use cases, and in general the <fieldset> element can also be used to section a form. Ideally, long forms should be spread across multiple pages, but if a form is getting long and must be on a single page, putting the different related sections inside different fieldsets improves usability.

Proposed exercise: Drink and hamburger

Using the code of the previous example, create a web page to choose the size of both a drink and a hamburger, each one inside a different <fieldset> with the corresponding <legend>. Also, as done before, the user should be able to choose among three different sizes: small, medium and large:

Drink

Hamburger

A form with sections

Beyond the structures specific to web forms, it’s good to remember that form markup is just HTML. This means that you can use all the power of HTML to structure a web form. As you can see in the examples, it’s common practice to wrap a label and its widget with a <p> element within. Lists are also recommended for structuring multiple checkboxes or radio buttons.

In addition to the <fieldset> element, it’s also common practice to use HTML titles (e.g. <h1>, <h2>) and sectioning (e.g. <section>) to structure complex forms. Above all, it is up to you to find a comfortable coding style that results in accessible, usable forms. Each separate section of functionality should be contained in a separate <section> element, with <fieldset> elements to contain radio buttons.

Let’s put these ideas into practice and build a slightly more involved form — a payment form. This form will contain more control types than the previous example. Read the descriptions carefully as you follow the below instructions, and start to form an appreciation of which wrapper elements we are using to structure the form, and why.

  1. First, we will create the form by adding the outer <form> element:
<form>
    ...
</form>
  1. Inside the <form> tags, we will add a heading and paragraph to inform users how required fields are marked:
<form>
  <h1>Payment form</h1>
  <p>Required fields are followed by <strong>*</strong>.</p>
  ...
</form>
  1. We’ll also add a simple <button> of type submit, at the bottom of the form, for submitting the form data:
<form>
  <h1>Payment form</h1>
  <p>Required fields are followed by <strong>*</strong>.</p>
  ...
  <p><button type="submit">Validate the payment</button></p>
</form>
  1. Next we’ll add a larger section of code into the form, below our previous entry. Here you’ll see that we are wrapping the contact information fields inside a distinct <section> element. Moreover, we have a set of three radio buttons, each of which we are putting in a new line. We also have two standard text <input> and their associated <label> elements, each contained inside a <p>, and a password input for entering a password:
<form>
  <h1>Payment form</h1>
  <p>Required fields are followed by <strong>*</strong>.</p>

  <section><fieldset>
    <legend><h2>Contact information</h2></legend>

    <fieldset>
      <legend>Title</legend>
      <label><input type="radio" name="title" value="mr" />Mr</label><br />
      <label><input type="radio" name="title" value="mrs" />Mrs</label><br />
      <label><input type="radio" name="title" value="miss" />Miss</label><br />
    </fieldset>

    <p><label>Name: <input type="text" name="name" required /> *</label></p>
    <p><label>E-mail: <input type="email" name="email" required /> *</label></p>
    <p><label>Password: <input type="password" name="password" required /> *</label></p>
  </fieldset></section>

  ...

  <p><button type="submit">Validate the payment</button></p>
</form>
  1. The second <section> of our form is the payment information. We have three distinct controls along with their labels, each contained inside a <p>. The first is a drop-down menu (<select>) for selecting credit card type. The second is an <input> element of type tel, for entering a credit card number; while we could have used the number type, we don’t want the number’s spinner UI. The last one is an <input> element of type date, for entering the expiration date of the card; this one will come up with a date picker widget in supporting browsers, and fall back to a normal text input in non-supporting browsers.
<form>
  <h1>Payment form</h1>
  <p>Required fields are followed by <strong>*</strong>.</p>

  <section><fieldset>
    <legend><h2>Contact information</h2></legend>
    <fieldset>
      <legend>Title</legend>
      <label><input type="radio" name="title" value="mr" />Mr</label><br />
      <label><input type="radio" name="title" value="mrs" />Mrs</label><br />
      <label><input type="radio" name="title" value="miss" />Miss</label> <br />
    </fieldset>
    <p><label>Name: <input type="text" name="name" required /> *</label></p>
    <p><label>E-mail: <input type="email" name="email" required /> *</label></p>
    <p><label>Password: <input type="password" name="password" required /> *</label></p>
  </fieldset></section>

  <section><fieldset>
    <legend><h2>Payment information</h2></legend>

    <p><label>Card type:
      <select name="card_type">
        <option value="visa">Visa</option>
        <option value="mc">Mastercard</option>
        <option value="amex">American Express</option>
      </select>
    </label></p>

    <p><label>Card number: <input type="tel" name="card_number" required /> *
    </label></p>

    <p><label>Expiration date: <input type="date" name="expiration" required /> *
    </label></p>
  </fieldset></section>

  <p><button type="submit">Validate the payment</button></p>
</form>

Proposed exercise: Payment form

Using the code of the example above, create a more sophisticated payment form. Inside the “Contact information” section, you have to add a group of radio buttons so that the user can select its status (either “Student”, “Teacher”, or “Other”), and a new text field to enter the phone number. And inside the “Payment information” section you have to add a new selection box so that the user can select the preferred payment type (either “Credit card” or “Paypal”) and a new email field to enter the Paypal account:

PAYMENT FORM (Required fields are followed by *)

Contact information
Status


Title






Payment information






A real example: search engine forms

Searching for text

Let’s now create a simple form which will provide all necessary data (a simple text) to be passed to some of the most known search engines:

<form action="https://google.com/search" method="GET">
  <label>Google: <input type="text" name="q" required /></label>
  <button type="submit">Search</button>
</form>
...
<form action="https://duckduckgo.com/" method="GET">
  <label>DuckDuckGo: <input type="text" name="q" required /></label>
  <button type="submit">Search</button>
</form>
...
<form action="https://bing.com/search" method="GET">
  <label>Bing: <input type="text" name="q" required /></label>
  <button type="submit">Search</button>
</form>

You will notice that when you press the submit button, the query (q parameter) is included in the url, and this way the search engine will know what to search. For example, if we are searching the word “dogs” on Google, the resulting url when submitting the form will be this one: https://www.google.es/search?q=dog.

Proposed exercise: Text search

Using the example of the form above to search information on Google, DuckDuckGo and Bing, develop a web page similar to the one below to search information on several search engines (at least five).

The only difference from one form to another is the value of the action attribute (“https://google.com/search”, “https://duckduckgo.com/”, “https://bing.com/search”, “https://www.ecosia.org/search”, “https://search.givewater.com/serp”, etc.). This address can be guessed by having a look at the url when you are using each particular search engine.

TEXT SEARCH

Searching for images

Now we will change the code a little bit so that the results provided by the search engines are images instead of text. In some cases we only need to change the action attribute, but sometimes we have to add some additional fields:

<form action="https://google.com/search" method="GET">
  <label>Gooogle: <input type="text" name="q" required /></label>
  <input type="hidden" name="tbm" value="isch" />
  <button type="submit">Search</button>
</form>
...
<form action="https://duckduckgo.com/" method="GET">
  <label>DuckDuckGo: <input type="text" name="q" required /></label>
  <input type="hidden" name="iax" value="images" />
  <input type="hidden" name="ia" value="images" />
  <button type="submit">Search</button>
</form>
...
<form action="https://search.givewater.com/serp" method="GET">
  <label>giveWater: <input type="text" name="q" required /></label>
  <input type="hidden" name="qc" value="images" />
  <button type="submit">Search</button>
</form>

You will notice that when you press the submit button, those hidden fields (which are not entered by the user) are included automatically in the url so that the search engine knows that has to show images instead of text. This way, in this example we are passing two parameters: q (the search string) and tbm (to search for images). For example, if we are searching for images about dogs on Google, the resulting url when submitting the form will be this one: https://www.google.es/search?q=dog&tbm=isch.

Proposed exercise: Image search

Using the code of the previous exercise, develop a new web page to search for images on several search engines (at least five).

To search for images using Bing and Ecosia, you only have to use the right value for the action attribute (“https://bing.com/images/search”, “https://www.ecosia.org/images”). You only have to use the hidden fields for Google (tbm), DuckDuckGo (iax, ia) and giveWater (qc), as done in the example above. Both the addresses and the hidden fields can be guessed by having a look at the url when you are using each particular search engine.

IMAGE SEARCH

Choosing between text and image search

Now let’s concentrate on Google’s search engine and let’s go one step forward to add a checkbox to give the user the option to choose between searching for text or images:

<form action="https://google.com/search">
  <label>Google: <input type="text" name="q" required /></label>
  <label>Search for images <input type="checkbox" name="tbm" value="isch" /></label>
  <button>Search</button>
</form>

Proposed exercise: Text or images

Develop a web page to search either text or images on Google and giveWater search engines. You have to provide the user with a checkbox so that can easily change from one type to another:

TEXT SEARCH

Filtering the results

Finally let’s concentrate again on Google’s search engine to add several controls so that the user can filter the results when searching for images. We will also add a reset button to set the default values:

<form action="https://google.com/search" method="GET">
  <p>Search: <input type="text" name="q" class="big" required /></p>

  <fieldset>
    <legend>Size</legend>
    <select name="tbs"> 
      <option selected disabled>Any size</option>
      <option value="isz:l">Large</option>
      <option value="isz:m">Medium</option>
      <option value="isz:i">Icon</option>
    </select>
  </fieldset>
  <fieldset>
    <legend>Color</legend>        
    <select name="tbs"> 
      <option selected disabled>Any color</option>
      <option value="ic:color">Color</option>
      <option value="ic:gray">Black and white</option>
      <option value="ic:trans">Transparent</option>
   </select>
  </fieldset> 
  <fieldset>       
    <legend>Type</legend>        
    <select name="tbs"> 
      <option selected disabled>Any type</option>
      <option value="itp:clipart">Clip art</option>
      <option value="itp:lineart">Line drawing</option>
      <option value="itp:animated">GIF</option>
    </select>
  </fieldset>  
  <fieldset>     
    <legend>Date</legend>        
    <select name="tbs"> 
      <option selected disabled>Any date</option>
      <option value="qdr:d">Past 24 hours</option>
      <option value="qdr:w">Past week</option>
    </select>
  </fieldset> 
  <fieldset>       
    <legend>License</legend>        
    <select name="tbs"> 
      <option selected disabled>Any license</option>
      <option value="il:cl">Creative commons</option>
      <option value="il:ol">Commercial and other</option>
    </select>
  </fieldset>

  <input type="hidden" name="tbm" value="isch" />

  <button type="reset">Reset</button>
  <button type="submit">Search</button>
</form>

As you will see, we have added many options to set different values for a parameter called “tbs” (we have guessed this parameter and all its possible values by looking at the url when searching for any information on Google). This way, in this example we are passing three parameters: q (the search string), tbm (to search for images) and tbs (to filter the results). For example, if we are searching for GIF images about dogs, the resulting url when submitting the form will be this one: https://www.google.es/search?q=dog&tbm=isch&tbs=itp:animated.

Also you will notice that inside each <select> element we are using a default option: <option selected disabled>...</option> so that by default, none of the available options are selected and the results are not filtered.

Proposed exercise: Filtering images with dropdown boxes

Using the code of the previous example, develop a web page to search for images on Google and filter the results using several dropdown boxes:

Search:

Size
Color
Type
Date
License

Proposed exercise: Filtering images with radio buttons

Create a new web page to search for images on Google and filter the results using radio buttons:

Search:

Size Large
Medium
Icon
Color Color
Black and white
Transparent
Type Clip art
Line drawing
GIF
Date Past 24 hours
Past week
License Creative commons
Commercial and other

Quiz

Test your skills with this quiz about HTML forms and some other concepts related to this unit.

HTML. Unit 9. Forms.

Introduction

This unit provides some instructions and examples that will help you to learn 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. In the sections listed below, we’ll cover all the essential aspects of Web forms including marking up their HTML structure, validating form data, and submitting data to the server.

What are web forms?

Web forms are one of the main points of interaction between a user and a web site or application. Forms allow users to enter data, which is generally sent to a web server for processing and storage, or used on the client side to immediately update the interface in some way (for example, add another item to a list, or show or hide a UI feature).

A web form’s HTML is made up of one or more form controls (sometimes called widgets), plus some additional elements to help structure the overall form — they are often referred to as HTML forms. The controls can be single or multi-line text fields, dropdown boxes, buttons, checkboxes, or radio buttons, and are mostly created using the <input> element, although there are some other elements to learn about too.

Form controls can also be programmed to enforce specific formats or values to be entered (form validation), and paired with text labels that describe their purpose to both sighted and blind users.

Basic native form controls

In the next sections we will mark up several functional web form examples, using some form controls and common structural elements, and focusing on accessibility best practices. Now we will look at the functionality of the different form controls, or widgets, in detail — studying all the different options available to collect different types of data. In this particular section we will look at the original set of form controls, available in all browsers since the early days of the web.

The <label> element

The <label> element is the formal way to define a label for an HTML form widget. This is the most important element if you want to build accessible forms. When implemented properly, screen readers will speak a form element’s label along with any related instructions, as well as being useful for sighted users. Take this example, where we nest the form control within the <label>, implicitly associating it:

<label>
  Name: <input type="text" name="name" />
</label>

With the <label> associated correctly with the <input> a screen reader will read out something like “Name, edit text”. If there is no label, or if the form control is neither implicitly or explicitly associated with a label, a screen reader will read out something like “Edit text blank”, which isn’t very helpful at all.

Labels are clickable, too!

Another advantage of properly setting up labels is that you can click or tap the label to activate the corresponding widget. This is useful for controls like text inputs, where you can click the label as well as the input to focus it, but it is especially useful for radio buttons and checkboxes. The hit area of such a control can be very small, so it is useful to make it as easy to activate as possible.

For example, clicking on the labels “I like cherry” or “I like banana” in the example below will toggle the selected state of the cherry or banana checkboxes respectively:

<label>
  <input type="checkbox" name="cherry" value="cherry" />
  I like cherry
</label><br />
<label>
  <input type="checkbox" name="banana" value="banana" />
  I like banana
</label><br />


Text input fields

Text <input> fields are the most basic form widgets. They are a very convenient way to let the user enter any kind of data because they can take many different forms depending on its type attribute value. It is used for creating most types of form widgets including single line text fields, time and date controls, controls without text input like checkboxes, radio buttons, and color pickers, and buttons too.

All basic text controls share some common behaviors:

  • They can be marked as required, to specify that a form field needs to be filled in before the form can be submitted.
  • They can be marked as readonly (the user cannot modify the input value but it is still sent with the rest of the form data) or disabled (the input value can’t be modified and is never sent with the rest of the form data).
  • They can have a placeholder. This is text that appears inside the text input box that should be used to briefly describe the purpose of the box.
  • They can be constrained in size (the physical size of the box) and minlength and maxlength (the minimum and maximum number of characters that can be entered into the box).
  • They can benefit from spell checking (using the spellcheck attribute), if the browser supports it.

Keep in mind that HTML form text fields are simple plain text input controls. This means that you cannot use them to perform rich editing (bold, italic, etc.). All rich text editors you’ll encounter are custom widgets created with HTML, CSS, and JavaScript.

Single line text fields

A single line text field is created using an <input> element whose type attribute value is set to text, or by omitting the type attribute altogether (text is the default value). The value text for this attribute is also the fallback value if the value you specify for the type attribute is unknown by the browser (for example if you specify type="color" and the browser doesn’t support native color pickers).

Let’s see this example using a couple of single line text fields:

<label>
  Name (5 to 10 characters):
  <input type="text" name="name" required
         minlength="5" maxlength="10" size="15" 
         placeholder="e.g. Fernando">
</label><br />
<label>
  Comment:
  <input type="text" name="comment" required
         placeholder="e.g. I like this example">
</label><br />


HTML5 enhanced the basic original single line text field by adding special values for the type attribute that enforce specific validation constraints and other features, for example specific to entering emails, URLs or numbers. We’ll cover those in a section below (The HTML5 input types).

Password field

One of the original input types was the password text field type:

<label>
  Password: <input type="password" name="password">
</label>

The password value doesn’t add any special constraints to the entered text, but it does obscure the value entered into the field (e.g. with dots or asterisks) so it can’t be easily read by others.

Keep in mind this is just a user interface feature; unless you submit your form securely, it will be sent in plain text, which is bad for security — a malicious party could intercept your data and steal passwords, credit card details, or whatever else you’ve submitted. The best way to protect users from this is to host any pages involving forms over a secure connection (i.e. at an https://... address), so the data is encrypted before it is sent.

Browsers recognize the security implications of sending form data over an insecure connection, and have warnings to deter users from using insecure forms. For more information on what Firefox implements, see Insecure passwords.

Multiple line text fields

The HTML <textarea> element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form:

<label>Tell us your story:
  <textarea name="story" rows="5">
    It was a dark and stormy night...
  </textarea>
</label>

You can use the rows and cols attributes to specify an exact size for the <textarea> to take. Setting these sometimes is a good idea for consistency, as browser defaults can differ. We also are using a default content (entered between the opening and closing tags), since <textarea> does not support the value attribute.

The <textarea> element also accepts several attributes common to form <input> element, such as autocomplete, autofocus, disabled, placeholder, readonly, and required.

Default values in text fields

Notice that the <input> tag is an empty element, meaning that it doesn’t need a closing tag. The <textarea> element however must be closed with the proper ending tag. This has an impact on a specific feature of forms: the way you define the default value. To define the default value of an <input> element you have to use the value attribute like this:

<input type="text" value="by default this element is filled with this text">

On the other hand,  if you want to define a default value for a <textarea>, you put it between the opening and closing tags of the <textarea> element, like this:

<textarea>
by default this element is filled with this text
</textarea>

Checkable items: checkboxes and radio buttons

Checkable items are controls whose state can be changed by clicking on them or their associated labels. There are two kinds of checkable item: the check box and the radio button. Both use the checked attribute to indicate whether the widget is checked by default or not.

It’s worth noting that these widgets do not behave exactly like other form widgets. For most form widgets, once the form is submitted all widgets that have a name attribute are sent, even if no value has been filled out. In the case of checkable items, their values are sent only if they are checked. If they are not checked, nothing is sent, not even their name. If they are checked but have no value, the name is sent with a value of on.

Checkbox

A check box is created using the <input> element with a type attribute set to the value checkbox. Elements of type checkbox are rendered by default as boxes that are checked (ticked) when activated, like you might see in an official government paper form. The exact appearance depends upon the operating system configuration under which the browser is running. Generally this is a square but it may have rounded corners. A checkbox allows you to select single values for submission in a form (or not).

Let’s see and try a very simple example:

<label>
  <input type="checkbox" name="carrots" value="carrots" checked />
  Do you like carrots?
</label>

Including the checked attribute makes the checkbox checked automatically when the page loads. Clicking the checkbox or its associated label toggles the checkbox on and off.

Due to the on-off nature of checkboxes, the checkbox is considered a toggle button. Many developers and designers are expanding the default checkbox styling to create buttons that look like toggle switches.

Radio button

A radio button is created using the <input> element with its type attribute set to the value radio. Elements of type radio are generally used in radio groups (collections of radio buttons describing a set of related options). Only one radio button in a given group can be selected at the same time. Radio buttons are typically rendered as small circles, which are filled or highlighted when selected.

Let’s see a simple example containing several radio buttons and how a browser may render it:

What is your favorite meal?<br />
<label>
  <input type="radio" name="meal" value="soup" checked />Soup
</label><br />
<label>
  <input type="radio" name="meal" value="curry" />Curry
</label><br />
<label>
  <input type="radio" name="meal" value="pizza" />Pizza
</label><br />
What is your favorite meal?



As seen above, several radio buttons can be tied together. If they share the same value for their name attribute, they will be considered to be in the same group of buttons. Only one button in a given group may be checked at a time; this means that when one of them is checked all the others automatically get unchecked. When the form is sent, only the value of the checked radio button is sent. If none of them are checked, the whole pool of radio buttons is considered to be in an unknown state and no value is sent with the form. Once one of the radio buttons in a same-named group of buttons is checked, it is not possible for the user to uncheck all of the buttons without resetting the form.

The <select> element

The HTML <select> element represents a control that provides a menu of options. For example:

<label>Choose the pet you most like:
  <select name="pets" id="pet-select">
    <option value="">--Please choose an option--</option>
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="hamster">Hamster</option>
    <option value="parrot">Parrot</option>
    <option value="spider">Spider</option>
    <option value="goldfish">Goldfish</option>
  </select>
</label>

The above example shows typical <select> usage. It is associated with a <label> for accessibility purposes, as well as a name attribute to represent the name of the associated data submitted to the server. Each menu option is defined by an <option> element nested inside the <select>.

Each <option> element should have a value attribute containing the data value to submit to the server when that option is selected. If no value attribute is included, the value defaults to the text contained inside the element. You can include a selected attribute on an element to make it selected by default when the page first loads.

The <select> element has some unique attributes you can use to control it, such as multiple to specify whether multiple options can be selected, and size to specify how many options should be shown at once. It also accepts most of the general form input attributes such as required, disabled, autofocus, etc.

File picker

There is one last <input> type that came to us in early HTML: the file input type. Forms are able to send files to a server (this specific action is also detailed in the Sending form data article). The file picker widget can be used to choose one or more files to send.

To create a file picker widget, you can use the <input> element with its type attribute set to file. The types of files that are accepted can be constrained using the accept attribute. In addition, if you want to let the user pick more than one file, you can do so by adding the multiple attribute.

In the following example, a file picker is created to request graphic image files. The user is allowed to select multiple files in this case:

<input type="file" name="file" accept="image/*" multiple />

On some mobile devices, the file picker can access photos, videos, and audio captured directly by the device’s camera and microphone by adding capture information to the accept attribute like so:

<input type="file" accept="image/*" capture="environment">
<input type="file" accept="video/*" capture="environment">
<input type="file" accept="audio/*" capture="user">

Buttons

The HTML <button> element represents a clickable button, used to submit forms or anywhere in a document for accessible, standard button functionality. By default, HTML buttons are presented in a style resembling the platform the browser runs on, but you can change buttons’ appearance with CSS.

The default behavior of the button can be changed with the type attribute. Possible values are:

  • submit: The button submits the form data to the server. This is the default if the attribute is not specified for buttons associated with the form or if the attribute contains an empty or an invalid value.
  • reset: The button resets all the controls to their initial values. You should use it only when necessary, since this behavior tends to annoy users.
  • button: The button has no default behavior, and does nothing when pressed by default. It can have client side scripts listen to the element’s events, which are triggered when the events occur.

Let’s see all types of buttons with a simple example:

<p>
  <label>Enter your comment: <input type="text" name="comment" required /></label>
</p>
<p>
  <button type="submit">This is a submit button</button>
</p>
<p>
  <button type="reset">This is a reset button</button>
</p>
<p>
  <button type="button">This is a simple button</button>
</p>

As you can see from the examples, <button> elements let you use HTML in their content, which is inserted between the opening and closing <button> tags. <input> elements on the other hand are empty elements; their displayed content is inserted inside the value attribute, and therefore only accepts plain text as content.

Proposed exercise: Native controls

Create a web page to show samples of all the input elements in this section: single line and multiple line text, password, checkboxes and radio buttons, select and file picker. You must include at least two examples of each of them. You have to use paragraphs and labels, and also the “required” attribute and all necessary field constraints have to be set for all of them. Check the result in your browser, and do not forget to include all basic HTML tags and validate your code. Finally, upload the code to your domain and check the result in your mobile phone.

Put all the tags inside a <form> container and use a submit button so that you can check that the fields are properly validated:
<form>
  <p><label>
    Name: <input type="text" name="name" required />
  </label></p>
  <p><label>
    Surname: <input type="text" name="surname" required />
  </label></p>
  <p><label>
    Password: <input type="password" name="password1" required />
  </label></p>
  <p><label>
    Repeat your password: <input type="password" name="password2" required />
  </label></p>
  ...
  <p><button>Submit</button></p>
</form>

HTML5 input types

In the previous section we looked at the <input> element, covering the original values of the type attribute available since the early days of HTML. Now we’ll look at the functionality of newer form controls in detail, including some new input types, which were added in HTML5 to allow collection of specific types of data.

E-mail address field

This type of field is set using the value email for the type attribute:

<label>
  Enter a valid email: 
  <input type="email" name="email" placeholder="e.g. [email protected]" required />
</label>

When this type is used, the user is required to type a valid email address into the field. Any other content causes the browser to display an error when the form is submitted. You can see this in action here:

You can also use the multiple attribute in combination with the email input type to allow several email addresses to be entered in the same input (separated by commas):

<label>
  Multiple emails: <input type="email" name="emails" multiple />
</label>

On some devices (notably touch devices with dynamic keyboards like smart phones) a different virtual keypad might be presented that is more suitable for entering email addresses, including the @ key. This is another good reason for using these newer input types, improving the user experience for users of these devices.

URL field

A special type of field for entering URLs can be created using the value url for the type attribute:

<label>
  Enter URL:
  <input type="url" name="url" placeholder="e.g. https://..." required />
</label>

It adds special validation constraints to the field. The browser will report an error if no protocol (such as http: is entered, or if the URL is otherwise malformed. You can see this in action here:

On devices with dynamic keyboards, the default keyboard will often display some or all of the colon, period, and forward slash as default keys.

Phone number field

A special field for filling in phone numbers can be created using tel as the value of the type attribute:

<label>
  Enter phone number:
  <input type="tel" name="tel" placeholder="e.g. 123 456 789" />
</label>

When accessed via a touch device with a dynamic keyboard, most devices will display a numeric keypad when type="tel" is encountered, meaning this type is useful whenever a numeric keypad is useful, and doesn’t just have to be used for telephone numbers.

Due to the wide variety of phone number formats around the world, this type of field does not enforce any constraints on the value entered by a user (this means it may include letters, etc.).

Numeric field

Controls for entering numbers can be created with an <input type="number"> This control looks like a text field but allows only floating-point numbers, and usually provides buttons in the form of a spinner to increase and decrease the value of the control. On devices with dynamic keyboards, the numeric keyboard is generally displayed.

With the number input type, you can constrain the minimum and maximum values allowed by setting the min and max attributes. You can also use the step attribute to set the increment increase and decrease caused by pressing the spinner buttons. By default, the number input type only validates if the number is an integer. To allow float numbers, specify step="any" If omitted, the step value defaults to 1, meaning only whole numbers are valid.

Let’s look at some examples. The first one below creates a number control whose value is restricted to any value between 1 and 10, and whose increase and decrease buttons change its value by 2:

<input type="number" name="age" min="1" max="10" step="2" value="1" />

The second one creates a number control whose value is restricted to any value between 0 and 1 inclusive, and whose increase and decrease buttons change its value by 0.01:

<input type="number" name="change" min="0" max="1" step="0.01" value="0" />

The <input type="number"> makes sense when the range of valid values is limited, for example a person’s age or height. If the range is too large for incremental increases to make sense (such as USA ZIP codes, which range from 00001 to 99999), the <input type="tel"> might be a better option; it provides the numeric keypad while forgoing the number’s spinner UI feature.

Slider controls

Another way to pick a number is to use a slider. You see these quite often on sites like house buying sites where you want to set a maximum property price to filter by. Let’s look at a live example to illustrate this:

Choose a maximum house price:

Usage-wise, sliders are less accurate than text fields. Therefore, they are used to pick a number whose precise value is not necessarily important.

A slider is created using the <input> with its type attribute set to the value range (<input type="range">). The slider-thumb can be moved via mouse or touch, or with the arrows of the keypad. It’s important to properly configure your slider. To that end, it’s highly recommended that you set the min, max, and step attributes which set the minimum, maximum and increment values, respectively.

Let’s look at the code behind the above example, so you can see how its done. First of all, the basic HTML:

<form>
  <p>Choose a maximum house price:</p>
  <input type="range" name="range"
         min="50000" max="500000" step="100" value="250000"
         oninput="number.value = this.value" />
  <input type="number" name="number"
         min="50000" max="500000" step="100" value="250000"
         oninput="range.value = this.value" />
</form>

This example creates a slider whose value may range between 50000 and 500000, which increments/decrements by 100 at a time. We’ve given it default value of 250000, using the value attribute.

One problem with sliders is that they don’t offer any kind of visual feedback as to what the current value is. This is why we’ve included an <input type="number"> element to contain the current value using some JavaScript code (we will go into this in a future unit).

Date and time pickers

Gathering date and time values has traditionally been a nightmare for web developers. For a good user experience, it is important to provide a calendar selection UI, enabling users to select dates without necessitating context switching to a native calendar application or potentially entering them in differing formats that are hard to parse. For example, the last minute of the previous millennium can be expressed in many different ways: 1999/12/31, 23:59, 12/31/99T11:59PM, etc.

HTML date controls are available to handle this specific kind of data, providing calendar widgets and making the data uniform.

A date and time control is created using the <input> element and an appropriate value for the type attribute, depending on whether you wish to collect dates, times, or both. Let’s look at the different available types in brief:

<p><label>
  Local date time: <input type="datetime-local" name="datetime" />
</label></p>
<p><label>
  Month: <input type="month" name="month">
</label></p>
<p><label>
  Time: <input type="time" name="time">
</label></p>
<p><label>
  Week: <input type="week" name="week">
</label></p>




All date and time controls can be constrained using the min and max attributes, with further constraining possible via the step attribute (whose value varies according to input type):

<label>
  When is your birthday?
  <input type="date" name="date" min="1975-01-01" max="2025-12-31" step="1" />
</label>

Color picker control

Colors are always a bit difficult to handle. There are many ways to express them: RGB values (decimal or hexadecimal), HSL values, keywords, and so on.

A color control can be easily created using the <input> element with its type attribute set to the value color. For example:

<label>
  Select color: <input type="color" name="color" />
</label>

When supported, clicking a color control will tend to display the operating system’s default color picking functionality for you to actually make your choice with. Here is a live example for you to try out:

Search field

Search fields are intended to be used to create search boxes on pages and apps. This type of field is set by using the value search for the type attribute:

<input type="search" name="search" placeholder="Search" required />

The main difference between a text field and a search field is how the browser styles its appearance. Often, search fields are rendered with rounded corners; they also sometimes display an “Ⓧ”, which clears the field of any value when clicked. Additionally, on devices with dynamic keyboards, the keyboard’s enter key may read “search”, or display a magnifying glass icon.

Another worth-noting feature is that the values of a search field can be automatically saved and re-used to offer auto-completion across multiple pages of the same website; this tends to happen automatically in most modern browsers.

Proposed exercise: HTML5 input types

Create a web page to show samples of all the input elements in this section: email, url, phone number, numeric field, slide control, date and time, color picker and search field. You must include at least two examples for each of them. You have to use paragraphs and labels, and also the “required” attribute and all necessary field constraints have to be set for all of them. Check the result in your browser, and do not forget to include all basic HTML tags and validate your code. Finally, upload the code to your domain and check the result in your mobile phone.

Put all the tags inside a <form> container and use a submit button so that you can check that the fields are properly validated:
<form>
  <p><label>
    Primary email: <input type="email" name="email1" required />
  </label></p>
  <p><label>
     Secondary email: <input type="email" name="email2" required />
  </label></p>
  <p><label>
     Your own website: <input type="url" name="website1" required />
  </label></p>
  <p><label>
    Your school's website: <input type="url" name="website2" required />
  </label></p>
  ...
  <p><button>Submit</button></p>
</form>

Your first “real” form

The section provides you with your very first experience of creating a real web form, including designing a simple form, implementing it using the right HTML form controls and other HTML elements, and describing how data is sent to a server. We’ll expand on each of these subtopics in more detail later.

Designing your form

Before starting to code, it’s always better to step back and take the time to think about your form. Designing a quick mockup will help you to define the right set of data you want to ask your user to enter. From a user experience (UX) point of view, it’s important to remember that the bigger your form, the more you risk frustrating people and losing users. Keep it simple and stay focused: ask only for the data you absolutely need.

Designing forms is an important step when you are building a site or application. It’s beyond the scope of this guide to cover the user experience of forms, but if you want to dig into that topic you should read the following articles:

In this section, we’ll build a simple contact form. Let’s make a rough sketch:

Our form will contain three text fields and one button. We are asking the user for their name, their e-mail and the message they want to send. Hitting the button will send their data to a web server.

Implementing your form

Let’s start creating the HTML for our form. We will use the following HTML elements: <form>, <label>, <input>, <textarea>, <button>.

The <form> element

All forms start with a <form> element, like this:

<form action="contact.php" method="get">

</form>

This element formally defines a form. It’s a container element and it also supports some specific attributes to configure the way the form behaves. All of its attributes are optional, but it’s standard practice to always set at least the action and method attributes:

  • The action attribute defines the location (URL) where the form’s collected data should be sent when it is submitted.
  • The method attribute defines which HTTP method to send the data with (usually GET or POST).

We’ll look at how those attributes work in our sending form data section later on.

The <label>, <input> and <textarea> elements

Our contact form is not complex: the data entry portion contains three text fields, each with a corresponding <label>:

In terms of HTML code we need something like the following to implement these form widgets:

<form action="contact.php" method="GET">
  <p>
    <label>Name: <input type="text" name="name" required /></label>
  </p>
  <p>
    <label>E-mail: <input type="email" name="email" required /></label>
  </p>
  <p>
    <label>Message: <textarea name="message" required></textarea></label>
  </p>
</form>

For usability and accessibility, we include an explicit label for each form control. There is great benefit to doing this — it associates the label with the form control, enabling mouse, trackpad, and touch device users to click on the label to activate the corresponding control, and it also provides an accessible name for screen readers to read out to their users.

On the <input> element, the most important attribute is the type attribute. This attribute is extremely important because it defines the way the <input> element appears and behaves:

  • In our simple example, we use <input type="text"> for the first input (the default value for this attribute). It represents a basic single-line text field that accepts any kind of text input.
  • For the second input, we use <input type="email"> which defines a single-line text field that only accepts a well-formed e-mail address. This turns a basic text field into a kind of “intelligent” field that will perform some validation checks on the data typed by the user. It also causes a more appropriate keyboard layout for entering email addresses (e.g. with an @ symbol by default) to appear on devices with dynamic keyboards, like smartphones.

Last but not least, note the syntax of <input> vs. <textarea></textarea> This is one of the oddities of HTML. The <input> tag is an empty element, meaning that it doesn’t need a closing tag. <textarea> is not an empty element, meaning it should be closed with the proper ending tag.

The <button> element

The markup for our form is almost complete; we just need to add a button to allow the user to send, or “submit”, their data once they have filled out the form. This is done by using the <button> element. We only need to add the following just above the closing </form> tag:

<button type="submit">Send your message</button>

As explained in a previous section, the <button> element also accepts a type attribute, with one of three values: submit, reset, or button:

  • A click on a submit button (the default value) sends the form’s data to the web page defined by the action attribute of the <form> element.
  • A click on a reset button resets all the form widgets to their default value immediately. From a UX point of view, this is considered bad practice, so you should avoid using this type of button unless you really have a good reason to include one.
  • A click on a button button does… nothing! That sounds silly, but it’s amazingly useful for building custom buttons, since you can define their chosen functionality with JavaScript.

Sending form data to your web server

The last part, and perhaps the trickiest, is to handle form data on the server side. The <form> element defines where and how to send the data thanks to the action and method attributes.

We provide a name to each form control. The names are important on both the client and server side; they tell the browser which name to give each piece of data and, on the server side, they let the server handle each piece of data by name. The form data is sent to the server as name/value pairs.

To name the data in a form you need to use the name attribute on each form widget that will collect a specific piece of data. Let’s look at our contact form again:

<form action="contact.php" method="GET">
  <p>
    <label>Name: <input type="text" name="name" required /></label>
  </p>
  <p>
    <label>E-mail: <input type="email" name="email" required /></label>
  </p>
  <p>
    <label>Message: <textarea name="message" required></textarea></label>
  </p>
  <p>
    <button type="submit">Send your message</button>
  </p>
</form>

In our example, the form will send 3 pieces of data named “name”, “email”, and “message”. That data will be sent to the URL “contact.php” using the HTTP GET method.

On the server side, the script at the URL “contact.php” will receive the data as a list of three key/value items contained in the HTTP request. The way this script will handle that data is up to you. Each server-side language (PHP, Python, Ruby, Java, C#, etc.) has its own mechanism of handling form data. It’s beyond the scope of this guide to go deeply into that subject for each language, but we will provide an example so that you can test your own forms using PHP.

Client-side form validation

Before submitting data to the server, it is important to ensure all required form controls are filled out, in the correct format. This is called client-side form validation, and helps ensure data submitted matches the requirements set for the various form controls.

Client-side validation is an initial check and an important feature of good user experience; by catching invalid data on the client-side, the user can fix it straight away. If it gets to the server and is then rejected, a noticeable delay is caused by a round trip to the server and then back to the client-side to tell the user to fix their data.

If you go to any popular site with a registration form, you will notice that they provide feedback when you don’t enter your data in the format they are expecting. You’ll get messages such as:

  • “This field is required” (You can’t leave this field blank).
  • “Please enter your phone number in the format xxxxxxxxx” (A specific data format is required for it to be considered valid).
  • “Please enter a valid email address” (the data you entered is not in the right format).
  • “Your password needs to be between 8 and 30 characters long and contain one uppercase letter, one symbol, and a number” (A very specific data format is required for your data).

This is called form validation. When you enter data, the browser and/or the web server will check to see that the data is in the correct format and within the constraints set by the application. Validation done in the browser is called client-side validation, while validation done on the server is called server-side validation. In this chapter we are focusing on client-side validation.

If the information is correctly formatted, the application allows the data to be submitted to the server and (usually) saved in a database; if the information isn’t correctly formatted, it gives the user an error message explaining what needs to be corrected, and lets them try again.

One of the most significant features of HTML5 form controls is the ability to validate most user data. This is done by using validation attributes on form elements. We’ve seen many of these earlier in the unit, but to recap:

  • required: Specifies whether a form field needs to be filled in before the form can be submitted.
  • minlength and maxlength: Specifies the minimum and maximum length of textual data (strings). You can constrain the character length of all text fields created by <input> or <textarea> using these attributes. A field is invalid if it has fewer characters than the minlength value or more than the maxlength value.
  • min and max: Specifies the minimum and maximum values of numerical input types.
  • type: Specifies whether the data needs to be a number, an email address, or some other specific preset type. 
  • pattern: Specifies a regular expression that defines a pattern the entered data needs to follow.

If the data entered in a form field follows all of the rules specified by the above attributes, it is considered valid. If not, it is considered invalid.

Further reading

We want to make filling out web forms as easy as possible. So why do we insist on validating our forms? There are three main reasons:

  • We want to get the right data, in the right format. Our applications won’t work properly if our users’ data is stored in the wrong format, is incorrect, or is omitted altogether.
  • We want to protect our users’ data. Forcing our users to enter secure passwords makes it easier to protect their account information.
  • We want to protect ourselves. There are many ways that malicious users can misuse unprotected forms to damage the application (see Website security).

Keeping this in mind, client-side validation should not be considered an exhaustive security measure! Your apps should always perform security checks on any form-submitted data on the server-side as well as the client-side, because client-side validation is too easy to bypass, so malicious users can still easily send bad data through to your server. Read Website security for an idea of what could happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind.

On the server side: retrieving the data

Whichever HTTP method you choose, the server receives a string that will be parsed in order to get the data as a list of key/value pairs. The way you access this list depends on the development platform you use and on any specific frameworks you may be using with it.

PHP offers some global objects to access the data. Assuming you’ve used the GET method, the example in the next sections just takes the data and saves it to a file. Of course, what you do with the data is up to you. You might display it, store it into a database, send it by email, or process it in some other way. We will use PHP to complete our examples.

The GET method

The GET method is the method used by the browser to ask the server to send back a given resource: “Hey server, I want to get this resource”. In this case, the browser sends an empty body. Because the body is empty, if a form is sent using this method the data sent to the server is appended to the URL.

Considering our contact form, and keeping in mind that GET method has been used, when we submit the form, we’ll see that the data appear in the URL at the browser address bar. For example, if you enter “Fernando” as the user name, “[email protected]” as the email address, and “Hello” as the message, and you press the submit button, your should see something like this in the address bar: “contact.php?name=Fernando&[email protected]&message=Hello“.

The data is appended to the URL as a series of name/value pairs. After the URL web address has ended, a question mark is included (?) followed by the name/value pairs, each one separated by an ampersand (&). In this case we are passing three pieces of data to the server:

  • name, which has a value of “Fernando”
  • email, which has a value of “[email protected]
  • message, which has a value of “Hello”
Proposed exercise: Contact form

Create a new web page with a contact form, using the code in the previous example. It should look like the one below (probably not so nice). Check the result in your browser and validate your code. Also try to send the data by pressing the button and check the URL inside the address bar. Finally set the minimum and maximum length of the text fields to any values you consider suitable to ensure the data in this form is correct before sending it to the server.

Note that if you press the submit button, you will go to the “contact.php” page, which is not implemented yet. At this point you will get an error, but your will see all the information in the URL, since we are using the GET method.

Proposed exercise: Full contact form

Let’s go ahead with some simple PHP code to save our data from the contact form. Create a file “contact.php” with the code below. Upload the form and the php code to your server and test your full example of the contact form to check that the messages are now saved into the server. Also tell some friends to test the web page and check that the data they have entered is also saved.

<?php
  // The global $_GET variable allows you to access the data sent with the GET method by name
  $name = $_GET['name'];
  $email = $_GET['email'];
  $message = $_GET['message'];

  // We put all data into the file "messages.csv" in a new line each time 
  file_put_contents("messages.csv", "$name;$email;$message\n", FILE_APPEND);

  // We show a link to the previous page and also to the file to check the results
  echo "<p>Data saved</p>";
  echo "<p>Click <a href='".$_SERVER['HTTP_REFERER']."'>here</a> to go back</p>";
  echo "<p>Click <a href='messages.csv' target='_blank'>here</a> to see all messages</p>";
?>
Proposed exercise: Greetings form

Create a new web page with a form similar to the one below, check the result in your browser and validate the code. Press the submit button and have a look at the browser address bar. After that enter another data different from the default values, press the submit button and check that the new URL contains the right information. Finally change the default value of both text fields (“Hi” and “Mom”) to use some other values, and check the result again.

Note that if you press the submit button, you will go to the “greetings.php” page, which is not implemented yet. At this point you will get an error, but your will see all the information in the URL, since we are using the GET method.
<form action="greetings.php" method="GET">
  <p>
    <label>
      What greeting do you want to say?: <input name="say" value="Hi" required />
    </label>
  </p>
  <p>
    <label>
      Who do you want to say it to?: <textarea name="to" required>Mom</textarea>
    </label>
  </p>
  <p>
    <button>Send my greetings</button>
  </p>
</form>
Proposed exercise: Full greetings form

Let’s go ahead with some simple PHP code to save our data from the greetings form. Create a file “greetings.php” with the code below. Upload the form and the php code to your server and test your full example of the greetings form to check that the greetings are now saved into the server. Also tell some friends to test the web page and check that the data they have entered is also saved.

You will see the similarities from the previous example (we have only changed the variables ($say and $to) and the file name where the data is saved (“greetings.csv”).
<?php
  // The global $_GET variable allows you to access the data sent with the GET method by name
  $say = $_GET['say'];
  $to = $_GET['to'];

  // We put all data into the file "greetings.csv" in a new line each time 
  file_put_contents("greetings.csv", "$say,$to\n", FILE_APPEND);

  // We show a link to the previous page and also to the file to check the results
  echo "<p>Data saved</p>";
  echo "<p>Click <a href='".$_SERVER['HTTP_REFERER']."'>here</a> to go back</p>";
  echo "<p>Click <a href='greetings.csv' target='_blank'>here</a> to see all messages</p>";
?>

The POST method

The POST method is a little different. It’s the method the browser uses to talk to the server when asking for a response that takes into account the data provided in the body of the HTTP request: “Hey server, take a look at this data and send me back an appropriate result”. If a form is sent using this method, the data is appended to the body of the HTTP request instead of the URL. It is more secure than the GET method, since when the form is submitted using the POST method, the data cannot be seen by any other person around. This method is recommended for example to be used in forms where a password is sent.

Let’s look at the following example, which is quite similar to the form in the GET section above, but with the method attribute set to POST and the type of the input box set to “password”:

<form action="login.php" method="POST">
  <p>
    <label>User: <input type="text" name="user" required /></label>
  </p>
  <p>
    <label>Password: <input type="password" name="password" required /></label>
  </p>
  <p>
    <button>Check user and password</button>
  </p>
</form>
Proposed exercise: Login form

Create a new web page with a login form, using the code in the previous example. It should look like the one below (probably not so nice). Check the result in your browser and validate your code. Also try to send the data by pressing the button and check if there is any information in the URL. Finally set the minimum length of the user text field to 5 and the maximum to 10, and do the same for the password field.

Note that if you press the submit button, you will go to the “login.php” page, which is not implemented yet. At this point you will get an error, but you will not see any information in the URL, since we are using the POST method.

Proposed exercise: Full login form

Let’s go ahead with some simple PHP code to check the user and the password from the login form. Create a file “login.php” with the code below. Upload the form and the php code to your server and test your full example of the login form to check the user (“admin”) and the password (“1234”). Also tell some friends to test your web page. After that, change the password from the file “login.php” and ask your friends to try to guess your new password. You must use a very simple password from “https://en.wikipedia.org/wiki/List_of_the_most_common_passwords” (otherwise your friends may be not able to guess it).

You will see the similarities from the previous example (we have only changed the variables ($user and $password) and we have used a condition to show an image with a thumb up or down, depending on whether the password is correct or not.
<?php
  // The global $_POST variable allows you to access the data sent with the POST method by name
  $user = $_POST['user'];
  $password = $_POST['password'];

  // Check the user and the password 
  if ($user == "admin" && $password == "1234") {
      echo "<img src='https://raw.githubusercontent.com/twbs/icons/main/icons/hand-thumbs-up.svg' width='100' />";
      echo "<p>Perfect! :-)</p><p>Click <a href='".$_SERVER['HTTP_REFERER']."'>here</a> to go back</p>";
  }
  else {
      echo "<img src='https://raw.githubusercontent.com/twbs/icons/main/icons/hand-thumbs-down.svg' width='100' />";
      echo "<p>Invalid user or password! :-(</p><p>Click <a href='".$_SERVER['HTTP_REFERER']."'>here</a> to try again</p>";
  }
?>

Quiz

Test your skills with this quiz about HTML forms and some other concepts related to this unit.

Test audio and video

If you are working with audio and video on the web, you may find useful some test resources in various formats and quality. This collection consists of various permissively licenced works you can use for testing purposes. As a bonus, they’re fun to watch and listen to.

Note that file sizes, compression and quality vary wildly. This is due to using different parameters when encoding, and the codecs themselves evolving over time.

Caminandes 3: Llamigos (2016)

It’s winter in Patagonia, food is getting scarce. Koro the Llama engages with Oti the pesky penguin in an epic fight over that last tasty berry.

Full movie (2 min, 30 sec)

  • 1080 px:
    • MP4 (24fps, H.264+AAC, 1920×1080) – 191MB
    • HEVC (24fps, H.265+AAC, 1920×1080) – 27MB
    • WEBM (24fps, VP9+Opus, 1920×1080) – 29MB
  • 720 px:
    • WEBM (24fps, VP9+Opus, 1280×720) – 22MB
    • MP4 (24fps, H.264+AAC, 1280×720) – 32MB
  • 480 px:
    • MP4 (24fps, H.264+AAC, 854×480) – 18MB

Images

Source 

Caminandes (Creative Commons Attribution)

Sintel (2010)

The film follows a girl named Sintel who is searching for a baby dragon she befriended.

Trailer (52 sec)

  • 1080 px:
    • DivX (24fps, H.264+AAC, 1920×818) – 27MB
    • MP4 (24fps, H.264+AAC, 1920×1080 letterbox) – 14MB
    • OGV (24fps, Theora+Vorbis, 1920×1080 letterbox) – 42MB
  • 720 px:
    • DivX (24fps, H.264+AAC, 1280×544) – 14MB
    • MP4 (24fps, H.264+AAC, 1280×720, letterbox) – 7.3MB
    • OGV (24fps, Theora+Vorbis, 1280×720, letterbox) – 22MB
  • 480 px:
    • DivX (24fps, H.264+AAC, 848×360) – 7.1MB
    • MP4 (24fps, H.264+AAC, 854×480, letterbox) – 4.2MB
    • OGV (24fps, Theora+Vorbis, 854×480, letterbox) – 12MB
  • Lossless original:
    • PNG (1920×1080, 1254 frames, letterbox) – 939MB
    • FLAC (stereo, 48kHz, 721kb/s) – 4.5MB

DivX versions include subtitles: en, fr

Full movie (14 min, 48 sec)

  • 4 K:
    • MKV (24fps, H.264+AC3, 4096×1744) – 4.2GB
    • HEVC (24fps, H.265+AAC, 4096×1744) – 426MB
  • 1080 px:
    • MKV (24fps, H.264+AC3, 1920×818) – 1.1GB
    • HEVC (24fps, H.265+AAC, 1920×820) – 128MB
  • 720 px:
    • MKV (24fps, H.264+AC3, 1280×544) – 650MB

Full movie includes subtitles: en, fr, de, es, it, nl, pl, pt, ru, vn

Images

Source 

Sintel – Blender open movie project (Creative Commons Attribution)

Audio

Licences: Creative Commons Attribution (CC-BY)

HTML. Unit 8. Video and audio content.

Introduction

Now that we are comfortable with adding text and simple images to a web page, the next step is to start adding video and audio players to your HTML documents! In this unit we’ll look at doing just that with the video and audio elements; we’ll then finish off by looking at how to add captions to your videos, and as a bonus, how to add maps to your pages.

Video and audio on the web

Web developers have wanted to use video and audio on the Web for a long time, ever since the early 2000s when we started to have bandwidth fast enough to support any kind of video (video files are much larger than text or even images). In the early days, native web technologies such as HTML didn’t have the ability to embed video and audio on the Web, so proprietary (or plugin-based) technologies like Flash (and later, Silverlight) became popular for handling such content. This kind of technology worked ok, but it had a number of problems, including not working well with HTML/CSS features, security and accessibility issues.

A native solution would solve much of this if implemented correctly. Fortunately, a few years later the HTML5 specification had such features added, with the <video> and <audio> elements, and some shiny new JavaScript APIs for controlling them. We’ll not be looking at JavaScript here — just the basic foundations that can be achieved with HTML.

We won’t be teaching you how to produce audio and video files — that requires a completely different skillset. For your own experimentation you can use some sample audio and video files as for example the ones available at “https://fernandoruizrico.com/test-audio-and-video/“.

The <video> element

The <video> element allows you to embed a video very easily. In the same way as for the <img> element, the src (source) attribute contains a path to the video you want to embed (it works in exactly the same way). You can also allow the users to be able to control video and audio playback through the controls attribute to include the browser’s own control interface. If this attribute is present, the browser will offer controls to allow the user to control video playback, including volume, seeking, and pause/resume playback. A really simple example looks like this:

<video src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_1080p.webm" controls></video>

You can insert a paragraph inside the video tag. This is called fallback content. It will be displayed if the browser accessing the page doesn’t support the <video> element, allowing us to provide a fallback for older browsers. This can be anything you like; in this case, we suggest providing a direct link to the video file, so the user can at least access it some way regardless of what browser they are using:

<video src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_1080p.webm" controls>
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p>
</video>

Width and height attributes

You can control the video size either with these attributes or with CSS. By setting the value in pixels of each attribute, you can choose to change either the width or the height of the video’s display area. In both cases, videos maintain their native width-height ratio — known as the aspect ratio. If the aspect ratio is not maintained by the sizes you set, the video will grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default. For example, to set the width of the video to 720px and maintain the aspect ratio:

<video width="720"
       src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_1080p.webm" 
       controls>
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p> 
</video>

Proposed exercise: Caminandes animated film

Create a web page with the previous example, and copy the code three times to show the same video three times in total. Change the width to set a different value for each video (1080, 720 and 480) and also change the src attribute accordingly. Finally, check the results in your browser (refresh your web page to assure that the browser is rendering the last changes in your code). Do not forget to include all necessary basic HTML tags and validate your code.

Videos:

https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_1080p.webm

https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_720p.webm

https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_480p.mp4

<video width="1080"
       src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_1080p.webm" 
       controls>
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p> 
</video>

<video width="720"
       src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_720p.webm" 
       controls>
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p> 
</video>

...

The poster attribute

You can set a URL for an image (poster attribute) to be shown while the video is downloading. If this attribute isn’t specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame. This image can be easily set like this:

<video width="1080"
       src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_1080p.webm" 
       poster="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/poster.jpg"
       controls>
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p> 
</video>

Proposed exercise: Caminandes animated film

Modify the code of the previous exercise, where you have the same video with three different sizes. Now you have to use the poster attribute to set three different images (you can find below the links to the posters, which are available at https://fernandoruizrico.com/test-audio-and-video/, or you can use any other images you like). When you finish, check the results in your browser (refresh your web page to assure that the browser is rendering the last changes in your code). Do not forget to include all necessary basic HTML tags and validate your code.

Posters:

https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/poster.jpg

https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/mine.png

https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/share.png

<video width="1080"
       src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_1080p.webm" 
       poster="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/poster.jpg"
       controls>
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p> 
</video>

<video width="720"
       src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_720p.webm" 
       poster="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/mine.png"
       controls>
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p> 
</video>

...

Media file support in browsers

Usually some codecs are used to compress video and audio into manageable files, since raw audio and video are both exceedingly large. Each web browser supports an assortment of codecs, which are used to convert the compressed audio and video into binary data and back. Each codec offers its own positive and negative features affecting your decisions about which to use. In order to maximize the likelihood that your web site or app will work on a user’s browser, you may need to provide each media file you use in multiple formats. If your site and the user’s browser don’t share a media format in common, your media simply won’t play.

One additional thing to keep in mind: mobile browsers may support additional formats not supported by their desktop equivalents, just like they may not support all the same formats the desktop version does. On top of that, both desktop and mobile browsers may be designed to offload handling of media playback (either for all media or only for specific types it can’t handle internally). This means media support is partly dependent on what software the user has installed.

So how do we do this? Take a look at the following updated example:

<video width="1080"
       poster="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/mine.png"
       controls>
  <source
    src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_1080p.webm"
    type="video/webm">
  <source
    src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_1080p.mp4"
    type="video/mp4">
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p> 
</video>

Here we’ve taken the src attribute out of the actual <video> tag, and instead included separate <source> elements that point to their own sources. In this case the browser will go through the <source> elements and play the first one that it has the codec to support. First WebM is tried. If that can’t be played, then MP4 is tried. Usually, including WebM and MP4 sources should be enough to play your video on most platforms and browsers these days. Also in the example, a fallback message is displayed if the video element isn’t supported, but not if all sources fail.

Each <source> element also has a type attribute. This is optional, but it is advised that you include it. The type attribute contains the MIME type of the file, and browsers can use the type to immediately skip videos they don’t understand. If type isn’t included, browsers will load and try to play each file until they find one that works, which obviously takes time and is an unnecessary use of resources.

You can refer to the Mozilla’s guide to media types and formats for help selecting the best containers and codecs for your needs, as well as to look up the right MIME types to specify for each.

Proposed exercise: Caminandes animated film

You have to modify the code of the previous exercise where you have three videos displaying the animated film “Caminandes”, each one with a different size and a different poster. You have to insert now a couple of source elements so that all three videos contain links for both the webm and mp4 codecs (you can find the links in the example below and also at https://fernandoruizrico.com/test-audio-and-video/). Check the results in your browser and do not forget to add all necessary HTML tags and validate your code.

Notice that the width of the video is set through the width attribute, and we have also used the poster attribute to set the image that will be displayed before the video is played:
<video width="1080"
       poster="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/mine.png"
       controls>
  <source
    src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_1080p.webm"
    type="video/webm">
  <source
    src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_1080p.mp4"
    type="video/mp4">
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p> 
</video>

<video width="720"
       poster="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/share.png"
       controls>
  <source
    src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_720p.webm"
    type="video/webm">
  <source
    src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_720p.mp4"
    type="video/mp4">
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p>
</video>

...

Proposed exercise: Sintel animated film

Create a new web page with the code below to show the “Sintel” animated film. After that, duplicate the code a couple of times to show three videos in total. Change the size of the videos to 1080, 720 and 480 and set the source elements accordingly (also remove the old src attribute, so that you get a similar code as the one shown in the example below). Finally change the poster image so that each video is displaying a different image when the page has just been loaded. You may find the links to both the videos and posters at https://fernandoruizrico.com/test-audio-and-video/, and also here:

Videos (1080 px):

https://fernandoruizrico.com/examples/test-media/video/sintel/trailer/sintel_trailer-1080p.mp4

https://fernandoruizrico.com/examples/test-media/video/sintel/trailer/sintel_trailer-1080p.ogv

Videos (720 px):

https://fernandoruizrico.com/examples/test-media/video/sintel/trailer/sintel_trailer-720p.mp4

https://fernandoruizrico.com/examples/test-media/video/sintel/trailer/sintel_trailer-720p.ogv

Videos (480 px):

https://fernandoruizrico.com/examples/test-media/video/sintel/trailer/sintel_trailer-480p.mp4

https://fernandoruizrico.com/examples/test-media/video/sintel/trailer/sintel_trailer-480p.ogv

Posters:

https://fernandoruizrico.com/examples/test-media/video/sintel/stills/poster.jpg

https://fernandoruizrico.com/examples/test-media/video/sintel/stills/scales.png

https://fernandoruizrico.com/examples/test-media/video/sintel/stills/dragon.png

<video 
  width="1080" controls
  poster="https://fernandoruizrico.com/examples/test-media/video/sintel/stills/scales.png">
  <source
    src="https://fernandoruizrico.com/examples/test-media/video/sintel/trailer/sintel_trailer-1080p.mp4"
    type="video/mp4">
  <source
    src="https://fernandoruizrico.com/examples/test-media/video/sintel/trailer/sintel_trailer-1080p.ogv"
    type="video/ogg">
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p>
</video>

...

Other <video> features

There are a number of other features you can include when displaying an HTML video. Take a look at our next example:

<video controls width="720"
       autoplay loop muted preload="auto" 
       poster="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/poster.jpg">
  <source src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_720p.webm" type="video/webm">
  <source src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_720p.mp4" type="video/mp4">
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p>
</video>

The autoplay attribute

A boolean attribute. If specified, the video automatically begins to play back as soon as it can do so without stopping to finish loading the data.

Important: You are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying (some browsers will not even allow the audio or video start playing right away). Keep in mind that sites that automatically play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible. If you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). However, this can be useful when creating media elements whose source will be set at a later time, under user control. See our autoplay guide for additional information about how to properly use autoplay.

The loop attribute

Makes the video (or audio) start playing again whenever it finishes. This can also be annoying, so only use if really necessary.

The muted attribute

A boolean attribute that indicates the default setting of the audio contained in the video. If set, the audio will be initially silenced. Its default value is false, meaning that the audio will be played when the video is played.

The preload attribute

This enumerated attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. It may have one of the following values:

  • none: Indicates that the video should not be preloaded.
  • metadata: Indicates that only video metadata (e.g. length) is fetched.
  • auto: Indicates that the whole video file can be downloaded, even if the user is not expected to use it.

Proposed exercise: Additional attributes

Following the previous examples, create a new web page with three videos you like, and set different values of the following attributes: loop, muted and preload. You can also try the autoplay attribute, although keep in mind that some browsers may have this feature disabled. Finally check the results in your browser and validate the code.

<video controls width="720"
       loop muted
       poster="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/poster.jpg">
  <source src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_720p.webm" type="video/webm">
  <source src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_720p.mp4" type="video/mp4">
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p>
</video>

<video controls width="720"
       loop preload="metadata"
       poster="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/stills/poster.jpg">
  <source src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_720p.webm" type="video/webm">
  <source src="https://fernandoruizrico.com/examples/test-media/video/caminandes-llamigos/caminandes_llamigos_720p.mp4" type="video/mp4">
  <p>Your browser doesn't support HTML5 video. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p>
</video>

...

Proposed exercise: Top ten videos

Create a web page to show the top ten videos you most like. You must set at least the width and poster attributes and also the source element to assure all of them are displayed in the right way as the previous examples.

You can find some sample videos at: https://senkorasic.com/testmedia/, https://archive.org/details/BigBuckBunny_124, https://archive.org/download/ElephantsDream/, https://tools.woolyss.com/html5-audio-video-tester/, https://test-videos.co.uk/, http://losplayer.com/?page_id=1880, https://dafftube.org/video-links/, https://github.com/mediaelement/mediaelement-files, http://techslides.com/sample-webm-ogg-and-mp4-video-files-for-html5, https://sample-videos.com/, http://samples.mplayerhq.hu/, https://www.clipcanvas.com/a/video-clip-formats-and-codec-samples, https://peach.blender.org/download/, https://download.blender.org/peach/bigbuckbunny_movies/, https://orange.blender.org/download/, https://github.com/mdn/learning-area/tree/master/html/multimedia-and-embedding/video-and-audio-content, etc.

The <audio> element

The HTML <audio> element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the <source> element: the browser will choose the most suitable one. It works just like the <video> element, with a few small differences as outlined below. A typical example might look like so:

<figure>
    <figcaption>Trance 2. Instrumental Background Music.</figcaption>
    <audio
        controls
        src="https://fernandoruizrico.com/examples/test-media/audio/Twisterium-Trance2.wav">
        <p>Your browser doesn't support HTML5 audio. Click <a href="https://fernandoruizrico.com/test-audio-and-video/">here</a> instead.</p>
    </audio>
</figure>

<figure>
    <figcaption>Space battle. Space Fantasy Spot Effect.</figcaption>
    <audio
        controls
        src="http://bbcsfx.acropolis.org.uk/assets/07042219.wav">
        <p>Your browser doesn't support HTML5 audio. Click <a href="http://bbcsfx.acropolis.org.uk">here</a> instead.</p>
    </audio>
</figure>

The above example shows simple usage of the <audio> element. In a similar manner to the <img> and <video> elements, we include a path to the media we want to embed inside the src attribute. We can include other attributes to specify information such as whether we want it to loop, whether we want to show the browser’s default audio controls, etc.

As with the <video> tag, the content inside the opening and closing <audio></audio> tags is shown as a fallback in browsers that don’t support the element.

This takes up less space than a video player, as there is no visual component — you just need to display controls to play the audio. Other differences from HTML video are as follows:

  • The <audio> element doesn’t support the width/height attributes — again, there is no visual component, so there is nothing to assign a width or height to.
  • It also doesn’t support the poster attribute — again, no visual component.

Proposed exercise: Sample audios

Following the previous example, create a web page to insert at least ten figures containing audio samples. Update the caption of each figure to show a brief description of each audio file, and check the results in your browser. Do not forget to add all necessary HTML basic tags and validate your code.

You can find thousands of audio samples at: http://bbcsfx.acropolis.org.uk/

The <iframe> element

By now you should really be getting the hang of embedding things into your web pages, including images, video and audio. At this point we will like to take somewhat of a sideways step, looking at an element that allow you to embed a wide variety of content types into your webpages: the <iframe> element.

Embed a video from Youtube

In this section we are going to jump straight into an active learning example to immediately give you a real idea of just what embedding technologies are useful for. The online world is very familiar with Youtube, but many people don’t know about some of the sharing facilities it has available. Let’s look at how Youtube allows us to embed a video in any page we like using an <iframe>:

  1. First, go to Youtube and find a video you like.
  2. Below the video, you’ll find a Share button — select this to display the sharing options.
  3. Select the Embed button and you’ll be given some <iframe> code — copy this.
<figure>
    <figcaption>Nyan Cat [original].</figcaption>
    <iframe width="560" height="315" src="https://www.youtube.com/embed/QH2-TGUlwu4" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</figure>

Proposed exercise: Top ten Youtube videos

Following the previous example, create a web page to insert at least ten figures containing videos from Youtube. Update the caption of each figure to show a brief description of each video, and check the results in your browser. Do not forget to add all necessary HTML basic tags and validate your code.

Embed a map from Google Maps

You will also find quite interesting embedding a Google Map. Let’s see how to do this with an example:

  1. Go to Google Maps and find a map you like.
  2. Click on the “Hamburger Menu” (three horizontal lines) in the top left of the user interface.
  3. Select the Share or embed map option.
  4. Select the Embed map option, which will give you some <iframe> code — copy this.
<figure>
    <figcaption>IES San Vicente.</figcaption>
    <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3126.6024620057733!2d-0.5317505844743932!3d38.4044398796498!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0xd6233fea3991575%3A0xf28fcef8c48c1513!2sIES%20San%20Vicente!5e0!3m2!1ses!2ses!4v1601811180214!5m2!1ses!2ses" width="600" height="450" frameborder="0" style="border:0;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe>
</figure>

Proposed exercise: Top ten locations

Following the previous example, create a web page to insert at least ten figures containing locations from Google Maps. Update the caption of each figure to show a brief description of each location, and check the results in your browser. Do not forget to add all necessary HTML basic tags and validate your code.

Quiz

Test your skills with this quiz about audio and video, and some other concepts related to this unit.

HTML. Unit 7. Advanced text formatting.

Introduction

There are many elements in HTML for formatting text, which we didn’t get to in previously. The elements described in this unit are less known, but still useful to know about. Here you’ll learn about marking up abbreviations, citations, quotations, computer code, mathematical equations and contact information.

Abbreviations

The HTML Abbreviation element (<abbr>) represents an abbreviation or acronym. The optional title attribute can provide an expansion or human-readable description for the abbreviation. This text is often presented by browsers as a tooltip when the mouse cursor is hovered over the element. If present, title must contain the full description and nothing else. Let’s look at some examples where we may use abbreviations or acronyms:

We use HTML to structure our web documents.
You can use CSS to style your HTML.
NASA sure does some exciting work.
Ashok’s joke made me LOL big time.

And now let’s see the HTML code we should write to get that result:

<p>We use <abbr title="Hypertext Markup Language">HTML</abbr> to structure our web documents.</p>

<p>You can use <abbr title="Cascading Style Sheets">CSS</abbr> to style your <abbr title="HyperText Markup Language">HTML</abbr>.</p>

<p><abbr title="National Aeronautics and Space Administration">NASA</abbr> sure does some exciting work.</p>

<p>Ashok's joke made me <abbr title="Laugh Out Loud">LOL</abbr> big time.</p>

The purpose of this element is purely for the convenience of the author and all browsers display it inline by default, though its default styling varies from one browser to another (this can be adjusted by adding some CSS code):

  • Some browsers, like Internet Explorer, do not style it differently than a <span> element.
  • Opera, Firefox, and some others add a dotted underline to the content of the element.
  • A few browsers not only add a dotted underline, but also put it in small caps.

Proposed exercise: Abbreviations example

Create a web page with the code of the previous example, add a couple of paragraphs with some abbreviations, and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

Proposed exercise: Abbreviations for chatting

The world of email, texting and instant messaging has given rise to a whole series of acronyms or abbreviations that allow texters to complete their messages more quickly. In this exercise you must write a couple of unordered lists. The first one will contain the list of the abbreviations listed below (and some other you may know). The second list will contain at least twenty sentences showing how those abbreviations may be used for chatting.

Also use <h1> and <h2> headers to precede the lists and show some descriptive text.

For example, the first list may show the abbreviations like this:

  • AFK – Away From Keyboard
  • BBIAB – Be Back In A Bit
  • BBL – Be Back Later
  • BBS – Be Back Soon
  • BRB – Be Right Back
  • BFF – Best Friends Forever
  • BTW – By The Way
  • COB – Close Of Business
  • DIY – Do It Yourself
  • DM – Direct Message
  • ETA – Estimated Time Of Arrival
  • FISH – First In, Still Here
  • IDK – I Don’t Know
  • IMO – In My Opinion
  • IRL – In Real Life
  • LMK – Let Me Know
  • LML – Laughing Mad Loud
  • LOL – Laughing Out Loud
  • NOYB – None of Your Business
  • OFC – Of Course
  • OMG – Oh My God
  • PANS – Pretty Awesome New Stuff
  • POS – Parents Over Shoulder
  • ROFL – Rolling On the Floor Laughing
  • SMH – Shaking My Head
  • TTYL – Talk To You Later
  • YOLO – You Only Live Once
  • WTH – What The Heck

The second list you have to show must contain at least twenty sentences where those abbreviations are used. For example:

  • This is my BFF, we have known each other since kindergarten.
  • BTW, the boss needs to see you in her office in five minutes.
  • She bought an old house that needs work because she loves DIY.
  • If you need more information just DM me.
  • What is the ETA on that report you are writing?
  • LOL. That is the funniest message I have ever received.
  • Did you see the game last night? I was shocked. I can’t believe the Lakers lost to the Phoenix Suns. SMH.

You may follow this source code as an example telling you how to markup both lists:

<h1>Some abbreviations I use to chat</h1>
<h2>The abbreviations</h2>
<ul>
    <li>AFK - Away From Keyboard</li>
    <li>BBIAB - Be Back In A Bit</li>
    <li>BBL - Be Back Later</li>
    <li>BBS - Be Back Soon</li>
    <li>...</li>
</ul>
<h2>Some examples</h2>
<ul>
    <li>This is my <abbr title="Best Friends Forever">BFF</abbr>, we have known each other since kindergarten.</li>
    <li><abbr title="By The Way">BTW</abbr>, the boss needs to see you in her office in five minutes.</li>
    <li>She bought an old house that needs work because she loves <abbr title="Do It Yourself">DIY<abbr>.</li>
    <li>If you need more information just <abbr title="Direct Message">DM</abbr> me.</li>
    <li>What is the <abbr title="Estimated Time of Arrival">ETA</abbr> on that report you are writing?</li>
    <li><abbr title="Laughing Out Loud">LOL</abbr>. That is the funniest message I have ever received.</li>
    <li>Did you see the game last night? I was shocked. I can’t believe the Lakers lost to the Phoenix Suns. <abbr title="Shaking My Head">SMH</abbr>.</li>
    <li>...</li>
</ul>

Citations

The <q> element

The HTML <q> element indicates that the enclosed text is a short inline quotation. Most modern browsers implement this by surrounding the text in quotation marks. You may also use the attribute cite to provide a URL that designates the source document or message for the information quoted, although this URL is not shown by the browser by default.

Let’s see a couple of examples by having a look at the result and the corresponding source code:

When Dave asks HAL to open the pod bay door, HAL answers: “I’m sorry, Dave. I’m afraid I can’t do that”.

According to Mozilla’s website, “Firefox 1.0 was released in 2004 and became a big success”.


<p>
    When Dave asks HAL to open the pod bay door, HAL answers: <q cite="https://www.imdb.com/title/tt0062622/quotes/qt0396921">I'm sorry, Dave. I'm afraid I can't do that</q>.
</p>

<p>
    According to Mozilla's website,
    <q cite="https://www.mozilla.org/en-US/about/history/details/">Firefox 1.0 was released in 2004 and became a big success</q>.
</p>

Important: The <q> element is intended for short quotations that don’t require paragraph breaks. For long quotations use the <blockquote> element.

Proposed exercise: Inline quotations

Create a web page with the code of the previous example, add one more paragraph with any quotation you like and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

You can get a quote for example from your preferred film, as in “https://www.starwars.com/news/15-star-wars-quotes-to-use-in-everyday-life“.

The <blockquote> element

The HTML <blockquote> element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation. A URL for the source of the quotation may be given using the cite attribute, while a text representation of the source can be given using the <cite> element. For example:

Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven’t found it yet, keep looking. Don’t settle. As with all matters of the heart, you’ll know when you find it. Steve Jobs

<blockquote cite="https://www.brainyquote.com/quotes/steve_jobs_416859">
    Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. As with all matters of the heart, you'll know when you find it.
    <cite><a href="https://www.brainyquote.com/quotes/steve_jobs_416859">Steve Jobs</a></cite>
</blockquote>

Proposed exercise: Famous quotes

Create a web page pointing to at least twenty of the most famous quotes. You may find some of them at “https://www.brainyquote.com“, “https://www.azquotes.com/“, or you can use any quotes you know, or from any other site.

You can use <blockquote> to wrap the full quote, and <cite> inside each quote to wrap the author’s name, as in the previous and following examples:
The greatest glory in living lies not in never falling, but in rising every time we fall. Nelson Mandela
The way to get started is to quit talking and begin doing. Walt Disney
Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped by dogma – which is living with the results of other people’s thinking. Don’t let the noise of others’ opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. Steve Jobs
If life were predictable it would cease to be life, and be without flavor. Eleanor Roosevelt
If you look at what you have in life, you’ll always have more. If you look at what you don’t have in life, you’ll never have enough. Oprah Winfrey

The <q> + <blockquote> + <cite> elements

The HTML Citation element (<cite>) is used to describe a reference to a cited creative work, and should include the title of that work. The reference may be in an abbreviated form according to context-appropriate conventions related to citation metadata. Let’s see an example where this element can be useful:

Hello and welcome to my motivation page. As Confucius’ quotes site says:

It does not matter how slowly you go as long as you do not stop.

I also love the concept of positive thinking, and the need to keep your thoughts positive (as mentioned in Positive quotes.)


And now let’s have a look at the source code we should write to get that result:

<h1>Motivation page</h1>
<p>Hello and welcome to my motivation page. As <a href="http://www.brainyquote.com/quotes/authors/c/confucius.html"><cite>Confucius' quotes site</cite></a> says:</p>

<blockquote cite="http://www.brainyquote.com/quotes/authors/c/confucius.html">
   <p>It does not matter how slowly you go as long as you do not stop.</p>
</blockquote>

<p>I also love the concept of positive thinking, and the need to <q cite="https://www.azquotes.com/quotes/topics/positive.html">keep your thoughts positive</q> (as mentioned in <a href="https://www.azquotes.com/quotes/topics/positive.html"><cite>Positive quotes</cite></a>.)</p>

Proposed exercise: Full quotations example

Create a web page with the code of the previous example, and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

Representing computer code

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. As explained in a previous unit, 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.

The <code> element

The HTML <code> element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code. By default, the content text is displayed using the default monospace font. For example:

The push() method adds one or more elements to the end of an array and returns the new length of the array.

The function selectAll() highlights all the text in the input field so the user can, for example, copy or delete the text.


<p>
    The <code>push()</code> method adds one or more elements to the end of an array and returns the new length of the array.
</p>

<p>
    The function <code>selectAll()</code> highlights all the text in the input field so the user can, for example, copy or delete the text.
</p>

Proposed exercise: Inline code

Create a web page with the code of the previous example, and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

The <pre> + <code> elements

The <code> element by itself only represents a single phrase of code or line of code. To represent multiple lines of code, we can wrap the <code> element within a <pre> element. For example:

if (a > b) {              // Example of code in
  console.log('Hello!');  // the JavaScript language
}
<pre><code>
if (a > b) {              // Example of code in
  console.log('Hello!');  // the JavaScript language
}
</code></pre>

Proposed exercise: Block code

Create a web page with the code of the previous example, add a new block with any piece of code of any language, and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

The <var> element

The HTML Variable element (<var>) represents the name of a variable in a mathematical expression or a programming context. It’s typically presented using an italic version of the current typeface, although that behavior is browser-dependent. For example:

A simple equation: x = y + 2

The volume of a box is l × w × h, where l represents the length, w the width and h the height of the box.

The variables minSpeed and maxSpeed control the minimum and maximum speed of the apparatus in revolutions per minute (RPM).


<p>
    A simple equation: <var>x</var> = <var>y</var> + 2
</p>

<p>
    The volume of a box is <var>l</var> × <var>w</var> × <var>h</var>, where <var>l</var> represents the length, <var>w</var> the width and <var>h</var> the height of the box.
</p>

<p>
    The variables <var>minSpeed</var> and <var>maxSpeed</var> control the minimum and maximum speed of the apparatus in revolutions per minute (RPM).
</p>

Proposed exercise: Equations and variables

Create a web page with the code of the previous example, add a new paragraph with any equation you like and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

The <kbd> element

The HTML Keyboard Input element (<kbd>) represents a span of inline text denoting textual user input from a keyboard, voice input, or any other text entry device. By convention, the browser renders the contents of a <kbd> element using its default monospace font. For example:

Please press Ctrl + Shift + R to re-render an MDN page.

Use the command help mycommand to view documentation for the command “mycommand”.

You can create a new document using the keyboard shortcut Ctrl + N.


<p>
    Please press <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd> to re-render an MDN page.
</p>

<p>
    Use the command <kbd>help mycommand</kbd> to view documentation for the command "mycommand".
</p>

<p>
    You can create a new document using the keyboard shortcut <kbd>Ctrl</kbd> + <kbd>N</kbd>.
</p>

Proposed exercise: Keyboard shortcuts

Create a web page with the code of the previous example, add a couple of paragraphs with any shortcuts you know, and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

The <samp> element

The HTML Sample Element (<samp>) is used to enclose inline text which represents sample (or quoted) output from a computer program. Its contents are typically rendered using the browser’s default monospaced font (such as Courir or Lucida Console). For example:

I was trying to boot my computer, but I got this hilarious message:

Keyboard not found
Press F1 to continue

When the process is complete, the utility will output the text Scan complete. Found N results. You can then proceed to the next step.


<p>I was trying to boot my computer, but I got this hilarious message:</p>
<p><samp>Keyboard not found <br>Press F1 to continue</samp></p>

...

<p>When the process is complete, the utility will output the text <samp>Scan complete. Found <em>N</em> results.</samp> You can then proceed to the next step.</p>

Proposed exercise: Sample output

Create a web page with the code of the previous example, and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

A full example

Let’s have a look at the following example which uses all these elements (find below the corresponding source code):

var para = document.querySelector('p');

para.onclick = function() {
  alert('Owww, stop poking me!');
}

You shouldn’t use presentational elements like <font> and <center>.

In the above JavaScript example, para represents a paragraph element.

Select all the text with Ctrl/Cmd + A.

$ ping mozilla.org
PING mozilla.org (63.245.215.20): 56 data bytes
64 bytes from 63.245.215.20: icmp_seq=0 ttl=40 time=158.233 ms

<pre><code>var para = document.querySelector('p');

para.onclick = function() {
  alert('Owww, stop poking me!');
}</code></pre>

<p>You shouldn't use presentational elements like <code>&lt;font&gt;</code> and <code>&lt;center&gt;</code>.</p>

<p>In the above JavaScript example, <var>para</var> represents a paragraph element.</p>

<p>Select all the text with <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + <kbd>A</kbd>.</p>

<pre>$ <kbd>ping mozilla.org</kbd>
<samp>PING mozilla.org (63.245.215.20): 56 data bytes
64 bytes from 63.245.215.20: icmp_seq=0 ttl=40 time=158.233 ms</samp></pre>

Proposed exercise: Code, shortcuts and output

Create a web page with the code of the previous example, and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

Proposed exercise: Linux commands

Create a web page to display a table with some of the most important linux commands, and their usage descripcion, more or less like the table below.

You have to use the <code> tag for the commands in the left column, and the <kbd> tag for the examples of user’s input. Also notice that the table has headers and caption.
Linux commands
Commands Description
passwd Changes your user password:
1. Type your old password
2. Insert new password
3. Confirm new password
~ User’s home directory
(short-cut for: /home/username)
ls Lists folders and files in current directory
mkdir Create new directory into the current one:
mkdir newdir
cd Changes directory:
cd test (go to a directory named ‘test’)
cd .. (go to parent directory)
cd ~ (go to home directory)
rm Removes specified file or directory:
rm filename (remove single filename)
rm *.txt (remove ALL .txt files into current directory)
rm -r dirname (remove directory and its files)

Please be careful when you use the -f option!
rmdir Removes specified EMPTY directory
rmdir dirname
pwd Prints current absolute path
man Shows specified command’s manual page:
man ls (shows ls help)
vi x.sh VI is a text editor. If x.sh does not exists, vi creates a new file called x.sh and opens it;
otherwise, it just opens the existing file.
less textfile less is a text pager. Opens (read only) textfile file. You can use up and down arrows to move across the text, shares many commands with VI.
chmod Changes POSIX permissions of a file or directory. Allows to protect files from unwanted access:
r : read permission
w : write permission
x : exec permission

chmod +x file.sh (allows execution)
chmod -w file.sh (denies write)
chown Changes owner of a file or directory:
chown username file.sh
top Shows current executing processes
cat Prints the content of a file on screen
grep Filters specified text file, and shows the lines that contains the pattern:
grep pattern file.sh
You can use also pipe the output of another command:
cat file.sh | grep home
cat file.sh | grep "home page"

Marking up contact details

HTML has an element for marking up contact details: <address>. It can be used in a variety of contexts, such as providing a business contact information in the page header or footer, or indicating the author of an article or post. This simply wraps around your contact details, for example:

<address>
  <p>Chris Mills, Manchester, The Grim North, UK</p>
</address>

The <address> element’s contents could also include more complex markup, and other forms of contact information. In fact, the data provided can take whatever form is appropriate for the context, and may include any type of contact information that is needed, such as a physical address, URL, email address, phone number, social media handle, geographic coordinates, and so forth. Just keep in mind that you should include at least the name of the person, people, or organization to which the contact information refers, for example:

<address>
  <p>
    Chris Mills<br />
    Manchester<br />
    The Grim North<br />
    UK
  </p>

  <ul>
    <li>Tel: 01234 567 890</li>
    <li>Email: [email protected]</li>
  </ul>
</address>

Note that something like this would also be ok, if the linked page contained the contact information:

<address>
    You can contact author at <a href="http://www.somedomain.com/contact">www.somedomain.com</a>.<br />
    If you see any bugs, please <a href="mailto:[email protected]">contact webmaster</a>.<br />
    You may also want to visit us:<br />
    Mozilla Foundation<br />
    331 E Evelyn Ave<br />
    Mountain View, CA 94041<br />
    USA
</address>

Proposed exercise: Contact information

Create a web page with the code of the previous examples and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

Figures

The HTML <figure> (Figure With Optional Caption) element represents self-contained content, potentially with an optional caption, which is specified using the (<figcaption>) element. The figure, its caption, and its contents are referenced as a single unit.

Figures with images

Dog asking for some food
Dog asking for some food

<!-- Just an image -->
<figure>
    <img src="https://developer.mozilla.org/static/img/favicon144.png"
         alt="The beautiful MDN logo.">
</figure>

<!-- Image with a caption -->
<figure>
    <img src="https://developer.mozilla.org/static/img/favicon144.png"
         alt="The beautiful MDN logo.">
    <figcaption>MDN Logo</figcaption>
</figure>

<!-- Another image with caption -->
<figure>
    <img src="https://picsum.photos/id/237/300/200"
         alt="Dog asking for some food">
    <figcaption>Dog asking for some food</figcaption>
</figure>

Proposed exercise: Images with captions

Create a web page with the code of the previous example, add a couple of figures with pictures, and choose a suitable caption for each one. Finally check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

You can use any pictures you like, for example from “https://picsum.photos/images“, as in other exercises from a previous unit.

Figures with poems

Bid me discourse, I will enchant thine ear,
Or like a fairy trip upon the green,
Or, like a nymph, with long dishevell’d hair,
Dance on the sands, and yet no footing seen:
Love is a spirit all compact of fire,
Not gross to sink, but light, and will aspire.

Venus and Adonis, by William Shakespeare

<figure>
    <p>
        Bid me discourse, I will enchant thine ear,<br />
        Or like a fairy trip upon the green,<br />
        Or, like a nymph, with long dishevell'd hair,<br />
        Dance on the sands, and yet no footing seen:<br />
        Love is a spirit all compact of fire,<br />
        Not gross to sink, but light, and will aspire.
    </p>
    <figcaption>
        <cite>Venus and Adonis</cite>, by William Shakespeare
    </figcaption>
</figure>

Proposed exercise: Poems

Create a web page with the code of the previous example, add a new figure with another poem you like, and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

Figures with code

Get browser details using navigator:
function NavigatorExample() {
    var txt;
    txt = "Browser CodeName: " + navigator.appCodeName + "; ";
    txt+= "Browser Name: " + navigator.appName + "; ";
    txt+= "Browser Version: " + navigator.appVersion  + "; ";
    txt+= "Cookies Enabled: " + navigator.cookieEnabled  + "; ";
    txt+= "Platform: " + navigator.platform  + "; ";
    txt+= "User-agent header: " + navigator.userAgent  + "; ";
    console.log("NavigatorExample", txt);
}

<figure>
<figcaption>Get browser details using <code>navigator</code>:</figcaption>
<pre><code>function NavigatorExample() {
    var txt;
    txt = "Browser CodeName: " + navigator.appCodeName + "; ";
    txt+= "Browser Name: " + navigator.appName + "; ";
    txt+= "Browser Version: " + navigator.appVersion  + "; ";
    txt+= "Cookies Enabled: " + navigator.cookieEnabled  + "; ";
    txt+= "Platform: " + navigator.platform  + "; ";
    txt+= "User-agent header: " + navigator.userAgent  + "; ";
    console.log("NavigatorExample", txt);
}</code></pre>
</figure>

Proposed exercise: Block code

Create a web page with the code of the previous example, and check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

Figures with quotations

Edsger Dijkstra:

If debugging is the process of removing software bugs, then programming must be the process of putting them in.

<figure>
    <figcaption><cite>Edsger Dijkstra:</cite></figcaption>
    <blockquote>
        If debugging is the process of removing software bugs,
        then programming must be the process of putting them in.
    </blockquote>
</figure>

Proposed exercise: Famous quotes

Create a web page with the code of the previous example, and add some famous quotes using the same format, to show at least ten quotes. Finally check the results in your browser. Do not forget to include the rest of the basic HTML tags, and validate your code.

You can use the same quotes you used in a previous exercise, or you can get some new ones from “https://www.brainyquote.com/“, “https://www.azquotes.com/“, or any other site you may know.

Quiz

Test your skills with this quiz about advanced text formatting and some other concepts related to this unit.

HTML. Unit 6. Tables.

Introduction

This unit will allow you to get started with HTML tables, covering the very basics such as rows and cells, headings, making cells span multiple columns and rows, and how to group together specific cells for a better markup and also for styling purposes in the future (using CSS).

What is a table?

A table is a structured set of data made up of rows and columns (tabular data). A table allows you to quickly and easily look up values that indicate some kind of connection between different types of data, for example a person and their age, or a timetable, or the information for several countries, as shown in this example:

Countries Capitals Population Language
USA Washington, D.C. 309 million English
Sweden Stockholm 9 million Swedish

Tables are very commonly used in human society, and have been for a long time, as evidenced by this US Census document from 1800:

It is therefore no wonder that the creators of HTML provided a means by which to structure and present tabular data on the web.

How can you build a table?

Let’s dive into a practical example and build up a simple table like this one:

1. Hi, I’m your first cell. 2. I’m your second cell. 3. I’m your third cell. 4. I’m your fourth cell.
5. Second row, first cell. 6. Second row, second cell. 7. Second row, third cell. 8. Second row, fourth cell.

Let’s build the table step by step:

  1. The content of every table is enclosed by these two tags : <table> ... </table>. We will put everything inside these tags:
<table>
    1. Hi, I'm your first cell.
    2. I'm your second cell.
    3. I'm your third cell.
    4. I'm your fourth cell.
    5. Second row, first cell.
    6. Second row, second cell.
    7. Second row, third cell.
    8. Second row, fourth cell.
</table>
  1. The smallest container inside a table is a table cell, which is created by a <td> element (‘td’ stands for ‘table data’). We will put the contents of each cell inside these tags:
<table>
    <td>1. Hi, I'm your first cell.</td>
    <td>2. I'm your second cell.</td>
    <td>3. I'm your third cell.</td>
    <td>4. I'm your fourth cell.</td>
    <td>5. Second row, first cell.</td>
    <td>6. Second row, second cell.</td>
    <td>7. Second row, third cell.</td>
    <td>8. Second row, fourth cell.</td>
</table>
  1. As you will see, the cells are not placed underneath each other, rather they are automatically aligned with each other on the same row. Each <td> element creates a single cell and together they make up the first row, and every cell we add makes the row grow longer. To stop this row from growing and start placing subsequent cells on a second row, we need to use the <tr> element (‘tr’ stands for ‘table row’). Let’s do this now (we will wrap each row in an additional <tr> element, with each cell contained in a <td>):
<table>
    <!-- First row -->
    <tr>
        <td>1. Hi, I'm your first cell.</td>
        <td>2. I'm your second cell.</td>
        <td>3. I'm your third cell.</td>
        <td>4. I'm your fourth cell.</td>
    </tr>

    <!-- Second row -->
    <tr>
        <td>5. Second row, first cell.</td>
        <td>6. Second row, second cell.</td>
        <td>7. Second row, third cell.</td>
        <td>8. Second row, fourth cell.</td>
    </tr>
</table>

Important: Table borders

By default, the browser will not show the borders of the tables. To get the borders shown, we must use some CSS code. By now, we will insert the following code in the <head> section of each html document we create (we will learn the meaning of this code in another unit):

<head>
    ...
    <style>
        table {
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    ...
</body>

Proposed exercise: Simple tables

Create a new web page, copy and paste a couple of times the table of the previous example and change the contents to get the following results:

Important: do not forget the small piece of CSS code inside the header section of your document to display the borders.
one two three four
five six seven eight
one two three
four five six
seven eight nine

Tables with images

You can insert any content you like inside the cells of a table. For example, images:

<table>
    <tr>
        <td><img src="https://picsum.photos/id/10/300/200" /></td>
        <td><img src="https://picsum.photos/id/1000/200/200" /></td>
    </tr>
    <tr>
        <td><img src="https://picsum.photos/id/1003/200/200" /></td>
        <td><img src="https://picsum.photos/id/1011/300/200" /></td>
    </tr>
</table>

Proposed exercise: Test pictures

Create a table of two columns and at least ten rows, and insert several pictures you like, as it is shown in the example above (with borders). Copy the same table in a new file and remove the CSS code to see the results now without borders.

You can use any image listed in “https://picsum.photos/images” . You only have to choose a picture and use the corresponding “id” and “size”. For example, “https://picsum.photos/id/1/200/200” is the image #1 (width=200px and height=200px) . Or “https://picsum.photos/id/103/300/200” is the image #103 (width=300px and height=200px).

Adding headers with <th> elements

Now let’s turn our attention to table headers. These are special cells that go at the start of a row or column and define the type of data that row or column contains. To illustrate why they are useful, have a look first at the following table:

Table without headers
Dog name Breed Age Eating Habits
Knocky Jack Russell 12 Eats everyone’s leftovers
Poppy Poodle 9 Nibbles at food
Buddy Streetdog 10 Hearty eater
Bailey Cocker Spaniel 5 Will eat till he explodes

The problem here is that, while you can kind of make out what’s going on, it is not as easy to cross reference data as it could be. If the column and row headings stood out in some way, it would be much better.

To recognize the table headers, both visually and semantically, you can use the <th> element (‘th’ stands for ‘table header’). This works in exactly the same way as a <td>, except that it denotes a header, not a normal cell. If we change all the <td> elements surrounding the table headers into <th> elements, the contents inside will be enhanced somehow by default. For example:

Table with headers
Dog name Breed Age Eating Habits
Knocky Jack Russell 12 Eats everyone’s leftovers
Poppy Poodle 9 Nibbles at food
Buddy Streetdog 10 Hearty eater
Bailey Cocker Spaniel 5 Will eat till he explodes

We will change the style of both <td> and <th> elements using CSS in future units. By now, let’s concentrate on the HTML code:

<table>
    <tr>
        <th>Dog name</th>
        <th>Breed</th>
        <th>Age</th>
        <th>Eating Habits</th>
    </tr>
    <tr>
        <th>Knocky</th>
        <td>Jack Russell</td>
        <td>12</td>
        <td>Eats everyone's leftovers</td>
    </tr>
    <tr>
        <th>Poppy</th>
        <td>Poodle</td>
        <td>9</td>
        <td>Nibbles at food</td>
    </tr>
    <tr>
        <th>Buddy</th>
        <td>Street dog</td>
        <td>10</td>
        <td>Hearty eater</td>
    </tr>
    <tr>
        <th>Bailey</th>
        <td>Cocker Spaniel</td>
        <td>5</td>
        <td>Will eat till he explodes</td>
    </tr>        
</table>

Proposed exercise: Dog walker

Create a web page with a table similar to the one in the previous example, to keep the information of all the clients of a dog walker. First you have to add three extra columns (to keep the name of the owners, their phone numbers, and the pictures of the dogs). After that you have to insert several rows to keep the data related to at least ten dogs.

In this case you can use another website to get test pictures about dogs: “https://placedog.net/images“. Open this URL and follow the instructions at the top of the page to insert each image. For example:
Dog name Owner Phone number Breed Age Eating Habits Picture
Knocky Fernando Ruiz 111222333 Jack Russell 12 Eats everyone’s leftovers
Poppy John Doe 222333444 Poodle 9 Nibbles at food
Buddy Peter Stark 333444555 Street dog 10 Hearty eater
Bailey Steve Doe 666777888 Cocker Spaniel 5 Will eat till he explodes

Adding a caption to your table with <caption>

You can give your table a caption by putting it inside a <caption> element and nesting that inside the <table> element. You should put it just below the opening <table> tag:

<table>
  <caption>Dinosaurs in the Jurassic period</caption>

  ...
</table>

As you can infer from the brief example above, the caption is meant to contain a description of the table contents. This is useful for all readers wishing to get a quick idea of whether the table is useful to them as they scan the page, but particularly for blind users. Rather than have a screenreader read out the contents of many cells just to find out what the table is about, he or she can rely on a caption and then decide whether or not to read the table in greater detail.

Proposed exercise: Simple table with caption and headers

Create a web page with a table similar to the one below, and insert some extra rows (at least ten).

Use a <caption> element to put the text “Simple table with headers”, and use the <th> element for the “First name” and “Last name” headers.
Simple table with headers
First name Last name
John Doe
Jane Doe

Proposed exercise: List of countries

Create a table with five columns and at least ten rows, and insert the data related to several countries. You can list for example the country names, their capitals, their population, the language, and several pictures, as done in the example at the beginning of the unit, but adding a new column to show an image. You have to use table headers (<th>) and caption (<caption>). Your table should look like shown below.

You can use again the website “https://picsum.photos/images” to get some random images for each country.
Countries I like
Countries Capitals Population Language Images
USA Washington, D.C. 309 million English
Sweden Stockholm 9 million Swedish

Row and column spanning

To provide additional control over how cells fit into (or span across) columns, both <th> and <td> support the colspan attribute, which lets you specify how many columns wide the cell should be, with the default being 1. Similarly, you can use the rowspan attribute on cells to indicate they should span more than one table row.

The following simple example shows a table listing people’s names along with various information about membership in a club or service. There are just four rows (including one header row), each with four columns (including one header column):

Name ID Member Since Balance
Margaret Nguyen 427311 0.00
Edvard Galinski 533175 37.00
Hoshi Nakamura 601942 15.00
<table>
  <tr>
    <th>Name</th>
    <th>ID</th>
    <th>Member Since</th>
    <th>Balance</th>
  </tr>
  <tr>
    <td>Margaret Nguyen</td>
    <td>427311</td>
    <td><time datetime="2010-06-03">June 3, 2010</time></td>
    <td>0.00</td>
  </tr>
  <tr>
    <td>Edvard Galinski</td>
    <td>533175</td>
    <td><time datetime="2011-01-13">January 13, 2011</time></td>
    <td>37.00</td>
  </tr>
  <tr>
    <td>Hoshi Nakamura</td>
    <td>601942</td>
    <td><time datetime="2012-07-23">July 23, 2012</time></td>
    <td>15.00</td>
  </tr>
</table>

Now, let’s introduce another column that shows the date the user’s membership ended, along with a super-heading above the “joined” and “canceled” dates called “Membership Dates”. This involves adding both row and column spans to the table, so that the heading cells can wind up in the right places. Let’s actually look at the output first:

Name ID Membership Dates Balance
Joined Canceled
Margaret Nguyen 427311 n/a 0.00
Edvard Galinski 533175 37.00
Hoshi Nakamura 601942 n/a 15.00

Notice how the heading area here is actually two rows, one with “Name”, “ID”, “Membership Dates”, and “Balance” headings, and the other with “Joined” and “Canceled”, which are sub-headings below “Membership Dates”. This is accomplished by:

  • Having the first row’s “Name”, “ID”, and “Balance” heading cells span two rows using the rowspan attribute, making them each be two rows tall.
  • Having the first row’s “Membership Dates” heading cell span two columns using the colspan attribute, which causes this heading to actually be two columns wide.
  • Having a second row of <th> elements that contains only the “Joined” and “Canceled” headings. Because the other columns are already occupied by first-row cells that span into the second row, these wind up correctly positioned under the “Membership Dates” heading.

The HTML is similar to the previous example’s, except for the addition of the new column in each data row, and the changes to the header. Those changes make the HTML look like this:

<table>
  <tr>
    <th rowspan="2">Name</th>
    <th rowspan="2">ID</th>
    <th colspan="2">Membership Dates</th>
    <th rowspan="2">Balance</th>
  </tr>
  <tr>
    <th>Joined</th>
    <th>Canceled</th>
  </tr>
  <tr>
    <th>Margaret Nguyen</td>
    <td>427311</td>
    <td><time datetime="2010-06-03">June 3, 2010</time></td>
    <td>n/a</td>
    <td>0.00</td>
  </tr>
  <tr>
    <th>Edvard Galinski</td>
    <td>533175</td>
    <td><time datetime="2011-01013">January 13, 2011</time></td>
    <td><time datetime="2017-04008">April 8, 2017</time></td>
    <td>37.00</td>
  </tr>
  <tr>
    <th>Hoshi Nakamura</td>
    <td>601942</td>
    <td><time datetime="2012-07-23">July 23, 2012</time></td>
    <td>n/a</td>
    <td>15.00</td>
  </tr>
</table>

The differences that matter here—for the purposes of discussing row and column spans—are in the first few lines of the code above. Note the use of rowspan to make the “Name”, “ID”, and “Balance” headers occupy two rows instead of just one, and the use of colspan to make the “Membership Dates” header cell span across two columns.

Proposed exercise: Your timetable

Create a web page to display your school timetable. You should create a table similar to the one below.

Notice that you have to use <th> elements for the headers, and colspan attribute for the BREAKS. You can also use the <strong> element to enhance the subject name in each cell.
Monday Tuesday Wednesday Thursday Friday
07:55h Computer Safety
Peter Williams
Computer Safety
Peter Williams
Computer Safety
Peter Williams
08:50h Network Services
Samuel Holland
Computer Safety
Peter Williams
Network Services
Samuel Holland
Computer Safety
Peter Williams
09:45h Network Operating Systems
Lucy Scott
Network Services
Samuel Holland
Web Applications
Fernando Ruiz
Network Services
Samuel Holland
Network Services
Samuel Holland
10:40h B R E A K
11:00h Network Operating Systems
Lucy Scott
Network Operating Systems
Lucy Scott
Business and Entrepreneurial Initiative
Rick Harris
Web Applications
Fernando Ruiz
Network Services
Samuel Holland
11:55h Business and Entrepreneurial Initiative
Rick Harris
Network Operating Systems
Lucy Scott
Network Operating Systems
Lucy Scott
Web Applications
Fernando Ruiz
Web Applications
Fernando Ruiz
12:50h B R E A K
13:10h Network Services
Samuel Holland
Business and Entrepreneurial Initiative
Rick Harris
Network Operating Systems
Lucy Scott
Network Operating Systems
Lucy Scott
Web Applications
Fernando Ruiz
14:05h Network Services
Samuel Holland
Web Applications
Fernando Ruiz
Network Operating Systems
Lucy Scott

Adding structure with <thead>, <tbody> and <tfoot>

As your tables get a bit more complex in structure, it is useful to give them more structural definition. One clear way to do this is by using <thead>, <tfoot> and <tbody>, which allow you to mark up a header, footer, and body section for the table. For example, we can improve the markup of any table by adding a simple header section like this:

The table header
First cell in the table body Second cell in the table body
<table>
    <thead>
        <tr>
            <th colspan="2">The table header</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>First cell in the table body</td>
            <td>Second cell in the table body</td>
        </tr>
    </tbody>
</table>

These new elements don’t make the table any more accessible to screen reader users, and don’t result in any visual enhancement on their own. They are however very useful for styling and layout, acting as useful hooks for adding CSS to your table. To give you some interesting examples, in the case of a long table you could make the table header and footer repeat on every printed page, and you could make the table body display on a single page and have the contents available by scrolling up and down.

To use all the elements together you just have to keep in mind the following considerations:

  • The <thead> element must wrap the part of the table that is the header (this is usually the first row containing the column headings, but this is not necessarily always the case).
  • The <tfoot> element needs to wrap the part of the table that is the footer (this might be a final row with items in the previous rows summed, for example). You can include the table footer right at the bottom of the table as you’d expect, or just below the table header (the browser will still render it at the bottom of the table).
  • The <tbody> element needs to wrap the other parts of the table content that aren’t in the table header or footer. It will appear below the table header or sometimes footer, depending on how you decided to structure it in the future.

The <thead> +<tbody> elements

Let’s add for example the <thead> and <tbody> sections to the table of the members of a club:

Name ID Membership Dates Balance
Joined Canceled
Margaret Nguyen 427311 n/a 0.00
Edvard Galinski 533175 37.00
Hoshi Nakamura 601942 n/a 15.00
<table>
  <thead>
    <tr>
      <th rowspan="2">Name</th>
      <th rowspan="2">ID</th>
      <th colspan="2">Membership Dates</th>
      <th rowspan="2">Balance</th>
    </tr>
    <tr>
      <th>Joined</th>
      <th>Canceled</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">Margaret Nguyen</td>
      <td>427311</td>
      <td><time datetime="2010-06-03">June 3, 2010</time></td>
      <td>n/a</td>
      <td>0.00</td>
    </tr>
    <tr>
      <th scope="row">Edvard Galinski</td>
      <td>533175</td>
      <td><time datetime="2011-01013">January 13, 2011</time></td>
      <td><time datetime="2017-04008">April 8, 2017</time></td>
      <td>37.00</td>
    </tr>
    <tr>
      <th scope="row">Hoshi Nakamura</td>
      <td>601942</td>
      <td><time datetime="2012-07-23">July 23, 2012</time></td>
      <td>n/a</td>
      <td>15.00</td>
    </tr>
  </tbody>
</table>

Proposed exercise: Club members

Create a web page to keep a listing of the members of a club as we have done in the example above. You can use the same source code as explained before, but you have to add a couple of columns: one to write the email address of each member, and the other to show their portraits (pictures). You also have to add several rows to the table so that it contains at least ten club members (you can use random names, dates and balances you make up on your own).

The <thead> +<tbody> +<tfoot> elements

Let’s put all these new elements into action with another table, where we will use all possible sections (<thead>, <tbody> and <tfoot>). Have a look at the following example:

How I chose to spend my money
Purchase Location Date Evaluation Cost (€)
SUM 118
Haircut Hairdresser 12/20 Great idea 30
Lasagna Restaurant 12/20 Regrets 18
Shoes Shoeshop 13/20 Big regrets 65
Toothpaste Supermarket 13/20 Good 5

We must put the obvious headers row inside a <thead> element, the “SUM” row inside a <tfoot> element, and the rest of the content inside a <tbody> element. You’ll see that adding the <tfoot> element has caused the “SUM” row to go down to the bottom of the table. And finally we will add a colspan attribute to make the “SUM” cell span across the first four columns, so the actual number appears at the bottom of the “Cost” column:

<table>
    <caption>How I chose to spend my money</caption>
    <thead>
        <tr>
            <th>Purchase</th>
            <th>Location</th>
            <th>Date</th>
            <th>Evaluation</th>
            <th>Cost (€)</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <td colspan="4">SUM</td>
            <td>118</td>
        </tr>
    </tfoot>
    <tbody>
        <tr>
            <td>Haircut</td>
            <td>Hairdresser</td>
            <td>12/20</td>
            <td>Great idea</td>
            <td>30</td>
        </tr>
        <tr>
            <td>Lasagna</td>
            <td>Restaurant</td>
            <td>12/20</td>
            <td>Regrets</td>
            <td>18</td>
        </tr>
        <tr>
            <td>Shoes</td>
            <td>Shoeshop</td>
            <td>13/20</td>
            <td>Big regrets</td>
            <td>65</td>
        </tr>
        <tr>
            <td>Toothpaste</td>
            <td>Supermarket</td>
            <td>13/20</td>
            <td>Good</td>
            <td>5</td>
        </tr>
    </tbody>
</table>

Proposed exercise: How to spend your money

Create a web page to write down how would you spend your money. You can use the same source code as the previous example, but you have to perform the following changes: add several rows with any things you would like to do (at least ten rows), and finally in the “Location” column you must use images instead of text.

You can use again the site “https://picsum.photos/images” to get the pictures of your preferred locations.

Proposed exercise: Captions

Add captions to those tables you have created previously and don’t have any caption yet. Do not forget to validate your code again.

Proposed exercise: Table structure

Add header, footer and body sections to all the tables you have created in previous exercises and don’t have those sections yet. Do not forget to validate your code again.

Quiz

Test your skills with this quiz about tables and some other concepts related to this unit.

HTML. Unit 5. Images.

Introduction

In the beginning, the Web was just text, and it was really quite boring. Fortunately, it wasn’t too long before the ability to embed images (and other more interesting types of content) inside web pages was added. There are other types of multimedia to consider, but it is logical to start with the humble <img> element, used to embed a simple image in a webpage. In this unit we’ll look at how to use it in depth, including the basics, annotating it with captions using <figure>.

How do we put an image on a webpage?

In order to put a simple image on a webpage, we use the <img> element. This is a void element (meaning that it has no text content or closing tag) that requires a minimum of one attribute to be useful: src (sometimes spoken as its full title, source). The src attribute contains a path pointing to the image you want to embed in the page, which can be a relative or absolute URL, in the same way as href attribute values in <a> elements.

So for example, if your image is called dinosaur.jpg and it sits in the same directory as your HTML page, you could embed the image like so:

<img src="dinosaur.jpg" />

If the image was in an images subdirectory, which was inside the same directory as the HTML page (which Google recommends for SEO/indexing purposes), then you’d embed it like this:

<img src="images/dinosaur.jpg" />

Search engines also read image filenames and count them towards SEO. Therefore, you should give your image a descriptive filename; dinosaur.jpg is better than img835.jpg.

You also could embed the image using its absolute URL, for example:

<img src="https://www.example.com/images/dinosaur.jpg" />
...
<img src="https://developer.mozilla.org/static/img/favicon144.png" />

Alternative text

The next attribute we’ll look at is alt. Its value is supposed to be a textual description of the image, to be used by search engines, and also in situations where the image cannot be seen/displayed or takes a long time to render because of a slow internet connection. Keep in mind that an alt attribute’s value should clearly and concisely describe the image’s content. For example, our above code could be modified like so:

<img src="images/dinosaur.jpg"
     alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth" />
...
<img src="https://developer.mozilla.org/static/img/favicon144.png"
     alt="MDN logo" />

The easiest way to test your alt text is to purposely misspell your filename. If for example our image name was spelled dinosoooor.jpg, the browser wouldn’t display the image, and would display the alt text instead.

So, why would you ever see or need alt text? It can come in handy for a number of reasons:

  • The user is visually impaired, and is using a screen reader to read the web out to them. In fact, having alt text available to describe images is useful to most users.
  • As described above, the spelling of the file or path name might be wrong.
  • The browser doesn’t support the image type. Some people still use text-only browsers, such as Lynx, which displays the alt text of images.
  • You may want to provide text for search engines to utilize; for example, search engines can match alt text with search queries.
  • Users have turned off images to reduce data transfer volume and distractions. This may be especially common on mobile phones, and in countries where bandwidth is limited or expensive.

What exactly should you write inside your alt attribute? It depends on why the image is there in the first place. In other words, what you lose if your image doesn’t show up:

  • Content. If your image provides significant information, provide the same information in a brief alt text – or even better, in the main text which everybody can see. Don’t write redundant alt text. How annoying would it be for a sighted user if all paragraphs were written twice in the main content? If the image is described adequately by the main text body, you can just use alt="".
  • Link. If you put an image inside <a> tags, to turn an image into a link, you still must provide accessible link text. In such cases you may, either, write it inside the same <a> element, or inside the image’s alt attribute – whichever works best in your case.
  • Text. You should not put your text into images. If your main heading needs a drop shadow, for example, use CSS for that rather than putting the text into an image. However, If you really can’t avoid doing this, you should supply the text inside the alt attribute.

Essentially, the key is to deliver a usable experience, even when the images can’t be seen. This ensures all users are not missing any of the content. Try turning off images in your browser and see how things look. You’ll soon realize how helpful alt text is if the image cannot be seen.

Width and height

You can use the width and height attributes to specify the width and height of your image. We could do this:

<img src="images/dinosaur.jpg"
     alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth"
     width="400"
     height="340" />

However, you shouldn’t alter the size of your images using always HTML attributes. If you set the image size too big, you’ll end up with images that look grainy, fuzzy, or too small, and wasting bandwidth downloading an image that is not fitting the user’s needs. The image may also end up looking distorted, if you don’t maintain the correct aspect ratio. You should use an image editor to put your image at the correct size before putting it on your webpage, but if you do need to alter an image’s size, you should use CSS instead.

Image titles

As with links, you can also add title attributes to images, to provide further supporting information if needed. In our example, we could do this:

<img src="images/dinosaur.jpg"
     alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth"
     title="A T-Rex on display in the Manchester University Museum" />

This gives us a tooltip on mouse hover, just like link titles. However, it should not be used as a replacement of the text inside the alt attribute. The title has a number of accessibility problems, mainly based around the fact that screen reader support is very unpredictable and most browsers won’t show it unless you are hovering with a mouse (so e.g. no access to keyboard users).

Proposed exercise: Embedding images

Create a web page to display several images. You have to use the basic <img> tag and the src attribute to point to the URL of each individual image. Por example, you can use images like these ones:

https://developer.mozilla.org/static/img/favicon144.png

https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg

https://validator.w3.org/images/w3c.png

You must also add some alt text to each image, and check that they work by misspelling the image URL’s. And finally experiment with different values of width and height to see what the effect is.

Image link

This example builds upon the previous ones, showing how to turn the image into a link. To do so, nest the <img> tag inside the <a>. You should use the alternative text to describe the resource the link is pointing to, as if you were using a text link instead:

<a href="https://developer.mozilla.org">
  <img src="https://developer.mozilla.org/static/img/favicon144.png"
       alt="Visit the MDN site" />
</a>

Proposed exercise: Top ten pages

Create a web page showing an ordered list (<ol>) of the top ten web pages you like. You must use images to create links to each page, and set the height attribute to the same value for all the images so that all of them are the same height. For example:

<ol>
  <li>
    <a href="https://developer.mozilla.org">
      <img src="https://developer.mozilla.org/static/img/favicon144.png" 
           alt="MDN site" height="100" />
    </a>
  </li>
  <li>
    <a href="https://validator.w3.org/">
      <img src="https://validator.w3.org/images/w3c.png" 
           alt="Markup Validation Service" height="100" />
    </a>
  </li>
  ...
</ol>

Annotating images with figures and figure captions

Speaking of captions, there are a number of ways that you could add a caption to go with your image. For example, there would be nothing to stop you from doing this:

<div class="figure">
  <img src="images/dinosaur.jpg"
       alt="The head and torso of a dinosaur skeleton;
            it has a large head with long sharp teeth"
       width="400"
       height="340">

  <p>A T-Rex on display in the Manchester University Museum.</p>
</div>

This is ok, since it contains the content you need, and can be nicely styled using CSS. But there is a problem here: there is nothing that semantically links the image to its caption, which can cause problems for screen readers. For example, when you have 50 images and captions, which caption goes with which image?

A better solution is to use the HTML5 <figure> and <figcaption> elements. These are created for exactly this purpose: to provide a semantic container for figures, and to clearly link the figure to the caption. Our above example could be rewritten like this:

<figure>
  <img src="images/dinosaur.jpg"
       alt="The head and torso of a dinosaur skeleton;
            it has a large head with long sharp teeth"
       width="400"
       height="340">

  <figcaption>A T-Rex on display in the Manchester University Museum.</figcaption>
</figure>

The <figcaption> element tells browsers, and assistive technology that the caption describes the other content of the <figure> element. From an accessibility viewpoint, captions and alt text have distinct roles. Captions benefit even people who can see the image, whereas alt text provides the same functionality as an absent image. Therefore, captions and alt text shouldn’t just say the same thing, because they both appear when the image is gone. Try turning images off in your browser and see how it looks.

Also keep in mind that a figure could be made of several images, a code snippet, audio, video, equations, a table, or something else. We will go through this in another unit.

Proposed exercise: Figures with captions

Create a web page to display several images you like, using the <figure> element, and add a caption to each one using the <figcaption> element, as it is done in the example below:

<figure>
  <img src="https://developer.mozilla.org/static/img/favicon144.png"
       alt="Mozilla developer website">
  <figcaption>MDN Logo</figcaption>
</figure>

<figure>
  <img src="https://validator.w3.org/images/w3c.png"
       alt="W3C Validator">
  <figcaption>W3C Logo</figcaption>
</figure>

...

Proposed exercise: Top ten films

Create a new web page showing an ordered list (<ol>) of the top ten films you like. In this case you must use figures with captions to create links to each page. Set the height attribute to the same value for all the images so that all of them are the same height. For example:

<ol>
  <li>
    <a href="https://en.wikipedia.org/wiki/Steve_Jobs_(film)">
      <figure>
        <img src="https://upload.wikimedia.org/wikipedia/commons/4/49/SteveJobsMacbookAir.JPG" 
             alt="Steve Jobs and Macbook Air" height="100" />
        <figcaption>Steve jobs</figcaption>
      </figure>
    </a>
  </li>
  <li>
    <a href="https://en.wikipedia.org/wiki/2001:_A_Space_Odyssey_(film)">
      <figure>
        <img src="https://upload.wikimedia.org/wikipedia/en/0/09/2001child2.JPG" 
             alt="Baby, space and Earth" height="100" />
        <figcaption>2001: A Space Odyssey</figcaption>
      </figure>
    </a>
  </li>
  ...
</ol>

Quiz

Test your skills with this quiz about images and some other concepts related to this unit.

HTML. Unit 4. Lists.

Introduction

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 (<ul> element)

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 in plain text as an example:

milk
eggs
bread
hummus

In HTML, unordered lists can be displayed like this:

  • milk
  • eggs
  • bread
  • hummus

To get that result and display the bulleted list, every unordered list starts off with a <ul> element (this wraps around all the list items). The last step is to wrap each list item in a <li> (list item) element:

<ul>
  <li>milk</li>
  <li>eggs</li>
  <li>bread</li>
  <li>hummus</li>
</ul>

Ordered lists (<ol> element)

Ordered lists are lists in which the order of the items does matter. Let’s take a set of directions in plain text as an example:

Drive to the end of the road
Turn right
Go straight across the first two roundabouts
Turn left at the third roundabout
The school is on your right, 300 meters up the road

In HTML, ordered lists can be displayed like this:

  1. Drive to the end of the road
  2. Turn right
  3. Go straight across the first two roundabouts
  4. Turn left at the third roundabout
  5. The school is on your right, 300 meters up the road

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>:

<ol>
  <li>Drive to the end of the road</li>
  <li>Turn right</li>
  <li>Go straight across the first two roundabouts</li>
  <li>Turn left at the third roundabout</li>
  <li>The school is on your right, 300 meters up the road</li>
</ol>

Proposed exercise: Hummus recipe

At this point you have all the information you need to mark up a recipe page example. Using the text below, create a new file and use the proper tags to improve the format of the hummus recipe:

Note: You must use <h1> for the main title, <h2> for the other titles, <p> for the paragraphs, <ul> for the ingredients, and <ol> for the instructions.
Quick hummus recipe

This recipe makes quick, tasty hummus, with no messing. It has been adapted from a number of different recipes that I have read over the years.

Hummus is a delicious thick paste used heavily in Greek and Middle Eastern dishes. It is very tasty with salad, grilled meats and pitta breads.

Ingredients

1 can (400g) of chick peas (garbanzo beans)
175g of tahini
6 sundried tomatoes
Half a red pepper
A pinch of cayenne pepper
1 clove of garlic
A dash of olive oil

Instructions

Remove the skin from the garlic, and chop coarsely
Remove all the seeds and stalk from the pepper, and chop coarsely
Add all the ingredients into a food processor
Process all the ingredients into a paste
If you want a coarse "chunky" hummus, process it for a short time
If you want a smooth hummus, process it for a longer time

For a different flavour, you could try blending in a small measure of lemon and coriander, chili pepper, lime and chipotle, harissa and mint, or spinach and feta cheese. Experiment and see what works for you.

Storage

Refrigerate the finished hummus in a sealed container. You should be able to use it for about a week after you've made it. If it starts to become fizzy, you should definitely discard it.

Hummus is suitable for freezing; you should thaw it and use it within a couple of months.

Nesting lists

It is perfectly ok to nest one list inside another one. You might want to have for example a sublist sitting below a top-level bullet:

  • first item
  • second item
    • second item first subitem
    • second item second subitem
    • second item third subitem
  • third item
<ul>
  <li>first item</li>
  <li>second item     
  <!-- Look, the closing </li> tag is not placed here! -->
    <ul>
      <li>second item first subitem</li>
      <li>second item second subitem</li>
      <li>second item third subitem</li>
    </ul>
  <!-- Here is the closing </li> tag -->
  </li>
  <li>third item</li>
</ul>

And you also might want to have an ordered list inside an unordered list:

  • first item
  • second item
    1. second item first subitem
    2. second item second subitem
    3. second item third subitem
  • third item
<ul>
  <li>first item</li>
  <li>second item
  <!-- Look, the closing </li> tag is not placed here! -->
    <ol>
      <li>second item first subitem</li>
      <li>second item second subitem</li>
      <li>second item third subitem</li>
    </ol>
  <!-- Here is the closing </li> tag -->
  </li>
  <li>third item</li>
</ul>

Let’s take a look now at the second list from our recipe example, and we will understand how useful nested lists can be:

<ol>
  <li>Remove the skin from the garlic, and chop coarsely.</li>
  <li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li>
  <li>Add all the ingredients into a food processor.</li>
  <li>Process all the ingredients into a paste.</li>
  <li>If you want a coarse "chunky" hummus, process it for a short time.</li>
  <li>If you want a smooth hummus, process it for a longer time.</li>
</ol>

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:

<ol>
  <li>Remove the skin from the garlic, and chop coarsely.</li>
  <li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li>
  <li>Add all the ingredients into a food processor.</li>
  <li>Process all the ingredients into a paste.
    <ul>
      <li>If you want a coarse "chunky" hummus, process it for a short time.</li>
      <li>If you want a smooth hummus, process it for a longer time.</li>
    </ul>
  </li>
</ol>

Proposed exercise: Hummus recipe

Using the previous proposed exercise of the hummus recipe, update the second list to use nested items to get the following result:

  1. Remove the skin from the garlic, and chop coarsely.
  2. Remove all the seeds and stalk from the pepper, and chop coarsely.
  3. Add all the ingredients into a food processor.
  4. Process all the ingredients into a paste.
    • If you want a coarse “chunky” hummus, process it for a short time.
    • If you want a smooth hummus, process it for a longer time.

Proposed exercise: Shopping list

Write your own shopping list, with at least 25 products. You must use types and subtypes, by wrapping the items in nested lists as the following example:

  • Bread
  • Milk
  • Coffee
  • Tea
    • Black tea
    • Green tea
  • Fruit
    • Oranges
    • Apples
<ul>
  <li>Bread</li>
  <li>Milk</li>
  <li>Coffee</li>
  <li>Tea
    <ul>
      <li>Black tea</li>
      <li>Green tea</li>
    </ul>
  </li>
  <li>Fruit
    <ul>
      <li>Oranges</li>
      <li>Apples</li>
    </ul>
  </li>
</ul>

Proposed exercise: Things to do

Create a new file containing a list of things to do, with at least 25 items. You must use nested lists mixing things and instructions, for example, by inserting ordered lists inside an unordered list, more or less like the example below:

  • Feed cat
    1. Wash the bowl
    2. Open cat food
    3. Deliver it to the cat
  • Wash car
    1. Vacuum interior
    2. Wash exterior
    3. Wax exterior
  • Grocery shopping
    1. Plan meals
    2. Clean out fridge
    3. Make list
    4. Go to the store
<ul>
   <li>Feed cat
     <ol>
       <li>Wash the bowl</li>
       <li>Open cat food</li>
       <li>Deliver it to the cat</li>
     </ol>
   </li>
   <li>Wash car
     <ol>
       <li>Vacuum interior</li>
       <li>Wash exterior</li>
       <li>Wax exterior</li>
     </ol>
   </li>
   <li>Grocery shopping
     <ol>
       <li>Plan meals</li>
       <li>Clean out fridge</li>
       <li>Make list</li>
       <li>Go to the store</li>
     </ol>
   </li>
</ul>

Description lists (<dl> element)

We have walked through how to mark up basic lists. Now we are going to mention the third type of list, which you will 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:

soliloquy

In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)

monologue

In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.

aside

In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information

Description lists use a different wrapper than the other list types, since they are delimited by the <dl> tag. 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:

<dl>
  <dt>soliloquy</dt>
  <dd>In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)</dd>

  <dt>monologue</dt>
  <dd>In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.</dd>

  <dt>aside</dt>
  <dd>In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought, or piece of additional background information.</dd>
</dl>

The browser will display description lists with the descriptions indented somewhat from the terms. Also note that it is permitted to have a single term with multiple descriptions, for example:

<dl>
  <dt>aside</dt>
  <dd>In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought, or piece of additional background information.</dd>
  <dd>In writing, a section of content that is related to the current topic, but doesn't fit directly into the main flow of content so is presented nearby (often in a box off to the side.)</dd>
</dl>

Proposed exercise: Coffee, Tea and Chocolate

It’s time to try your hand at description lists. Create a new file and add elements to the raw text below so that it appears as a description list:

Coffee

Coffee is a brewed beverage with a distinct aroma and flavor prepared from the roasted seeds of the Coffea plant.

Tea

Tea is an aromatic beverage commonly prepared by pouring hot or boiling water over cured leaves of the tea plant.

Hot chocolate

Hot chocolate (also known as hot cocoa) is a heated beverage typically consisting of shaved chocolate, melted chocolate or cocoa powder, heated milk or water, and sugar.

Proposed exercise: Bacon, Eggs and Coffee

Create a new file with the text below and add elements to the raw text so that it appears as a description list. You could try using your own terms and descriptions if you like:

Bacon

Cured meat prepared from a pig.

Eggs

Common food and one of the most versatile ingredients used in cooking.

Coffee

The drink that gets the world running in the morning.
A light brown color.

Proposed exercise: Computer hardware

Write a definition list to explain the meaning of the following terms: Central processing unit, monitor, mouse, keyboard, graphics card, sound card, speakers and motherboard.

Quiz

Test your skills with this quiz about text formatting and some other concepts related to this unit.

HTML. Unit 3. Hyperlinks.

What is a hyperlink

Hyperlinks are one of the most important innovations the Web has to offer. They’ve been a feature of the Web since the beginning, and they 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. These links are also known as URL’s, or Uniform Resource Locators, text strings that specify where a resource (such as a web page, image, or video) can be found on the Internet.

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 (https://www.bbc.com/) 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.

The <a> element

The <a> element (or anchor element) with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address. Content within each <a> should indicate the link’s destination.

Links also provide implicitly some information about the navigation activity, as they will appear as follows in all browsers by default:

  • An unvisited link is underlined and blue
  • A visited link is underlined and purple
  • An active link is underlined and red

A basic link is created by wrapping the text or other content, inside an <a> element and using the href attribute, also known as a Hypertext Reference, or target, that contains the web address:

<p>
    I'm creating a link to
    <a href="https://www.mozilla.org/en-US/">the Mozilla homepage</a>.
</p>

The code above gives as the following result: I’m creating a link to the Mozilla homepage.

Adding information with the title attribute

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:

<p>
    I'm creating a link to
    <a href="https://www.mozilla.org/en-US/" 
       title="The best place to find more information about Mozilla's mission and how to contribute">the Mozilla homepage</a>.
</p>

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.

Keep in mind that 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 as a regular text.

Proposed exercise: Links with information

Create a web page containing the information below. Use a main <h1> heading, a couple of paragraphs, and links to the pages in the list.

Note: you must also use the title attribute to display information about each link on mouse hover.
Alicante

Amongst the most notable features of the city are the Castle of Santa Bárbara, which sits high above the city, and the port of Alicante. The latter was the subject of bitter controversy in 2006–2007 as residents battled, successfully, to keep it from being changed into an industrial estate.

The Santa Bárbara castle is situated on Mount Benacantil, overlooking the city. The tower (La Torreta) at the top, is the oldest part of the castle, while part of the lowest zone and the walls were constructed later in the 18th century.

URLs and paths

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 simply 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 level index.html) pointing to contacts.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 is contacts.html:

<p>Want to contact a specific staff member?
Find details on our <a href="contacts.html">contacts page</a>.</p>

Moving down into subdirectories

If you wanted to include a hyperlink inside index.html (the top level index.html) pointing to projects/index.html, you would need to go down into the projects 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 is projects/index.html:

<p>Visit my <a href="projects/index.html">project homepage</a>.</p>

Moving back up into parent directories

If you wanted to include a hyperlink inside projects/index.html pointing to pdfs/project-brief.pdf, you’d have to go up a directory level, then back down into the pdf directory. To go up a directory, use two dots — .. — so the URL you would use is ../pdfs/project-brief.pdf:

<p>A link to my <a href="../pdfs/project-brief.pdf">project brief</a>.</p>

You can combine multiple instances of these features into complex URLs, if needed, for example: ../../../complex/path/to/my/file.html.

Proposed exercise: Navigation menu

Create an “index.html” file to link your pages together with a navigation menu to create a multi-page website. This index file will link to all of your pages you have created before. Have a look at the example below so that you can get an idea of how your source code should look like. Additionally, you must also use the title attribute to insert a description of what it is inside each file linked.

Note: From now on, each time you create a new file for any exercise, you should link it from your “index.html” file, and of course, you must validate everything each time you change something in your code or your domain.
<h1>HTML exercises</h1>

<h2>Headings and paragraphs</h2>

<p><a href="headings_paragraphs_1.html">Headings and paragraphs example 1</p>
<p><a href="headings_paragraphs_2.html">Headings and paragraphs example 2</p>
...

<h2>Text formatting</h2>

<p><a href="text_formatting_1.html">Text formatting example 1</p>
<p><a href="text_formatting_2.html">Text formatting example 2</p>
...

Document fragments

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:

<h2 id="mailing_address">Mailing address</h2>

Then to link to that specific id, you’d include it at the end of the URL, preceded by a hash symbol (#), for example:

<p>Want to write us a letter? Use our <a href="contacts.html#mailing_address">mailing address</a>.</p>

You can even use the document fragment reference on its own to link to another part of the same document:

<p>The <a href="#mailing_address">company mailing address</a> can be found at the bottom of this page.</p>

Proposed exercise: Table of contents

Create a page similar to this one: https://en.wikipedia.org/wiki/Alicante (you may choose any page you like containing a large table of contents). You must start with an index, which must be followed by several sections (at least 10), each one preceded with a heading and containing several paragraphs. Also insert several links in each paragraph, as it is done in Wikipedia (fill the title attribute too). Have a look at this example and do something similar on your own:

<h1>Alicante</h1>

<p><a href="#geography">Geography</a></p>
<p><a href="#history">History</a></p>
...

<h2 id="geography">Geography</h2>

Alicante is located in the southeast of the <a href="https://en.wikipedia.org/wiki/Iberian_Peninsula">Iberian Peninsula</a>, on the shores of the <a href="https://en.wikipedia.org/wiki/Mediterranean_Sea">Mediterranean Sea</a>.
...

<h2 id="history">History</h2>

The area around Alicante has been inhabited for over 7000 years. The first tribes of <a href="https://en.wikipedia.org/wiki/Hunter-gatherer">hunter-gatherers</a> moved down gradually from Central Europe between 5000 and 3000 BC. Some of the earliest settlements were made on the slopes of <a href="https://en.wikipedia.org/wiki/Mount_Benacantil">Mount Benacantil</a>.
...

Block level links

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 (we will learn more about using images in a future unit):

<a href="https://www.mozilla.org/en-US/">
  <img src="mozilla-image.png" alt="mozilla logo that links to the mozilla homepage">
</a>

Proposed exercise: Image as a link

Using the image https://iessanvicente.com/ies_san_vicente.jpg, create a link to the url https://iessanvicente.com so that when you click on the picture, you will jump to the web page of IES San Vicente.

Note: you must use the full url of the image as the src attribute of the <img> element.

E-mail links

It is 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 to mailto:.

In its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. For example:

<a href="mailto:[email protected]">Send email to nowhere</a>

This code 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 simply “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.

Specifying details

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:

<a href="mailto:[email protected][email protected]&[email protected]&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email">
  Send mail with cc, bcc, subject and body
</a>

Keep in mind that 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.

Proposed exercise: E-mail links

Create a web page to display the following links (use paragraphs so that each link is shown in a different line):

mailto:
mailto:[email protected]
mailto:[email protected],[email protected]
mailto:[email protected][email protected]
mailto:[email protected][email protected]&subject=This%20is%20the%20subject

Quiz

Test your skills with this quiz about text formatting and some other concepts related to this unit.

HTML. Unit 2. Text formatting.

Introduction

In order to make the structure of our text clearer, we can mark some elements to make them more relevant than other elements. In HTML there are some tags for this purpose:

<b>Bold text</b>
<strong>Important text</strong>
<i>Italic text</i>
<em>Emphasized text</em>
<mark>Marked (or highlighted) text</mark>
<small>Small text</small>
<del>Deleted text</del>
<ins>Inserted text</ins>
<sub>Subscript text</sub>
<sup>Superscript text</sup>

The <b> and <strong> elements

The <b> element represents a piece of bold text to which attention is being drawn, but it does not add any extra importance. On the other hand, the text inside the <strong> element is displayed in bold too, but it also adds a strong importance to the text, which could be meaningfull when the web page is analyzed and processed to extract important words or expressions. This kind of text analysis is done for example by some search engines, which need to know what any page is about to include it in the results when a user is searching for pages containing specific keywords.

Proposed exercise: Important text

Create a web page with the text below using a header and a paragraph, and also add extra importance to several words inside the paragraph:

Doctors without borders

In May 1968, a group of young doctors decided to go and help victims of wars and major disasters. This new brand of humanitarianism would reinvent the concept of emergency aid. They were to become Médecins Sans Frontières (MSF), known internationally in English as Doctors Without Borders.

The <i> and <em> elements

The <i> element defines a part of the text in an alternate voice or mood, and the content inside is usually displayed in italic. It is often used to indicate a technical term, a phrase from another language, a thought, etc. On the other hand, the HTML <em> defines an emphasized text, which is displayed in italic too, but the result is different when a screen reader is used, since the words inside the <em> tag will be pronounced with an emphasis, using verbal stress.

Proposed exercise: Emphasized text

Create a web page with the text below using a header and a couple paragraphs, and also emphasize several words inside the paragraphs:

People first

MSF was officially created on December 22, 1971. At the time, 300 volunteers made up the organization: doctors, nurses, and other staff, including the 13 founding doctors and journalists.

MSF was created on the belief that all people have the right to medical care regardless of gender, race, religion, creed, or political affiliation, and that the needs of these people outweigh respect for national boundaries.

The <del> and <ins> elements

The <del> element is used to define a text which has been deleted from a document. Search engines sometimes use this tag to show the changes inside a website, when some text has been removed after the developer has uploaded a new version.

On the other hand, the <ins> element is used to define a text which has been inserted into a document. Search engines sometimes use this tag to show the changes inside a website, when some text has been replaced after the developer has uploaded a new version.

It depends on the browser how to display the text inside these elements, but most of them will strike a line through deleted text, and will underline the inserted text by default.

Proposed exercise: Deleted and inserted text

Create a page to show several paragraphs where some words or sentences were previously said, but now the authors have changed their minds and want to tell their readers a new version of their thoughts. Using the <del> and <ins> tags, show the previous texts and the new ones in a way that makes clear that the new text is replacing the first one. The result should look like this (you should write at least 10 paragraphs):

The Earth is flat rounded.

On 31 December 2020 the whole world is going to end! carry on as usual.

...

The <mark> element

The <mark> element represents text which is marked or highlighted for reference or notation purposes, due to the marked passage’s relevance or importance in the enclosing context.

Proposed exercise: Highlighted text

Create a web page with the text below using a header and a couple paragraphs, and also highlight several words or figures inside the paragraphs:

Building MSF

Since 1980, MSF has opened offices in 28 countries and employs more than 30,000 people across the world. Since its founding, MSF has treated over a hundred million patients. 

MSF has also maintained itsinstitutional and financial independence, and the organization has continued to be critical of both itself and the broader aid system when appropriate, all in the name of trying to help direct more effective and timely aid to those who need it most.

Proposed exercise: Highlighted text

Create a web page with the following text and highlight the “salamander” word in the last two paragraphs:

Search results for "salamander":

Several species of salamander inhabit the temperate rainforest of the Pacific Northwest.

Most salamanders are nocturnal, and hunt for insects, worms, and other small creatures.

Proposed exercise: Highlighted text

Create a web page with the following heading and paragraph, and mark the text “Rebel spies managed to steal secret plans”:

Star Wars Episode IV - A New Hope

It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire. During the battle, Rebel spies managed to steal secret plans to the Empire’s ultimate weapon, the DEATH STAR, an armored space station with enough power to destroy an entire planet.

The <sub> and <sup> elements

The <sub> and <sup> elements specify inline text which should be displayed as subscript (or superscript) for solely typographical reasons. Subscripts are typically rendered with a lowered baseline using smaller text, and superscripts are usually rendered with a raised baseline using smaller text.

Proposed exercise: Subscripts

Create a web page to display the following text:

One of my favorite molecules is C8H10N4O2, also known as "caffeine".

The horizontal coordinates' positions along the X-axis are represented as x1 ... xn.

Proposed exercise: Subscripts

Create a page to display the chemical formula of some common compounds, applying subscript formatting to the numbers (you must print each compound in a different paragraph, using the <p> element). The result should look like this (you must add some other compounds on your own):

Oxygen: O2
Water: H2O
Carbon dioxide: CO2
Vinegar: C2H4O2
Baking soda: NaHCO3
Sugar: C12H22O11
Alcohol: C2H5OH
...

Proposed exercise: Superscripts

Create a web page to display the following text:

The Pythagorean theorem is often expressed as the following equation: a2 + b2 = c2

One of the most common equations in all of physics is: E = mc2

The ordinal number "fifth" can be abbreviated in English as follows: 5th

Proposed exercise: Superscripts

Print the squares of the numbers 1 – 25. Each number should be on a separate line (using the <br /> element), next to it the number 2 superscripted, an equal sign and the result. Something like this should be displayed:

12 = 1
22 = 4
...
252 = 625

The <span> element

If we need to mark a text but we consider that none of the existing tags is a good option, we can use the <span> element. Thus, we can isolate a piece of text although there are no changes in the appearence of the text marked when using it on its own (<span>...</span>). The advantage of this tag comes when it is used together with some attributes like class or style, combined with some CSS code. We will work on this deeply in the future, but by now, let’s have a look for example at this code, where we use a <span> element to color only a part of the text inside a paragraph:

<p>My mother has <span style="color:blue">blue</span> eyes.</p>

Proposed exercise: Text color

Using the <p> and <span> elements, create a web page to display the color of the eyes (e.g. blue, brown, green, gray) of some people you know.

Quiz

Test your skills with this quiz about text formatting and some other concepts related to this unit.