Embedded Content: Video, Audio, and Canvas

HTML5 introduces a swathe of new tags to accommodate the increasingly interactive and multimedia nature of the Web. While there have been numerous ways to embed video, audio, and dynamic imagery in the past, the new web standard attempts to make this easier, more consistent, and more reliable.

The simplest embedded (foreign) content is an image, applied to a web page with the img element. In the olden days, object, along with various plugins and proprietary devil dust, was used to bash and smash video and audio into submission. Although not without its (compatibility) problems, there is now a much better method for using various types of media in web pages.

Video


<video src="kitties.mp4" controls></video>

Bam. There you go. Just like that. Simple.

This will embed a video, complete with controls, in browsers that support the HTML5 video tag and the video content type.

The controls attribute is optional but if you don’t want it – if you really want to take control away from the user – you can just slap in an autoplay attribute:


<video src="kitties.mp4" autoplay></video>

This will play the video on page load, won’t display any controls, and will most likely annoy the hell out of your visitors. Of course you could, if you were kind, put in both the controls and autoplay attributes.

Other basic attributes at your disposal include width, height, loop, and muted.


<video src="kitties.mp4" width="300" height="200" loop muted autoplay controls></video>

Poster

You can specify a placeholder image, which will be displayed before the video is played, with the poster attribute.


<video src="kitties.mp4" poster="fluffy.jpg" controls></video>

The specified image will stretch or shrink to fit the dimensions of the video, regardless of the original size of the image.

Fall-back content

So, yes, there is an opening and closing tag. Whatever could go in between them? Why, fall-back content: content that is displayed if the browser doesn’t understand the video element. That could be a few words, a chunk of HTML, or a “really funny” and “highly original” Lolcats image.


<video src="kitties.mp4" controls>
    <img src="hahahaha.jpg" alt="Hilarious cat and caption saying 'soz'.">
</video>

Alternative content

As already noted, it’s not only compatibility with the tag we need to worry about, but also compatibility with the source video itself. Luckily, more than one video source file can be offered up with the source element along with indications of the requirements of the file in the value of the type attribute. The browser will then take the first one it’s happy with.


<video controls>
    <source src="kitties.mp4" type="video/mp4; codecs='avc1, mp4a'">
    <source src="kitties.webm" type="video/webm; codecs='vp8.0, vorbis'">
    <p>Browser no likey HTML 5.</p>
</video>

Here, a browser should figure out if it can handle the “video/mp4” MIME type and if it has the stated codec to decipher it. If it doesn’t, it should move on to the next and try again with the details set out in the second source element.

Audio

Applying audio is just like applying video. Using the audio tag, the structure is the same as using video and the attributes src, controls, autoplay and loop can all be used in the same way.


<audio src="meow_mix.mp3" controls>
    Your stupid browser doesn't support HTML 5 audio.
</audio>

Alternative content can also be defined in exactly the same way as with the video and source tags.

Canvas

A major addition to HTML5 is the canvas element. It is designed to provide a canvas onto which JavaScript can be used to paint all manner of dynamic images such as graphs, animated sprites, or daft cat pictures.


<canvas id="wittykitty" width="800" height="450">
    <!-- Fall-back content here, just like with video and audio -->
</canvas>

That’s it. That’s the extent of the actual HTML, at least – the power is in the scripting.

HTML5 Forms Pt. 2: Attributes and Data Lists

Continuing from HTML5 Forms Pt. 1, in addition to the multitude of fresh new input types, there are also additional form-specific attributes at your disposal as well as data lists, a sort of text/select hybrid.

More attributes

As well as those attributes mentioned, both here and in earlier guides, there is a handful of additional attributes:

Placeholder text

The placeholder attribute can be used with text input fields (and their text-like cousins, such as type="email" and type="number") as well as textarea elements. It is intended as a hint, rather than a label, for which a label element should still be used.


<label for="email_address">Email address</label>
<input type="email" placeholder="you@somewhere.com" name="email_address" id="email_address">

Autofocus

You might want focus to land on a form field when a page loads. If you think of a search engine, for example, when you land on its home page you don’t normally need to click on the search box to start typing – you can do so straight away because it already has focus. The autofocus attribute is a quick way to achieve this effect.


<input name="query" autofocus>

Data lists

A data list takes the form of a list of suggestions that accompanies a text field:


<input name="country" list="country_name">
<datalist id="country_name">
    <option value="Afghanistan">
    <option value="Albania">
    <option value="Algeria">
    <option value="Andorra">
    <option value="Armenia">
    <option value="Australia">
    <option value="Austria">
    <option value="Azerbaijan">
    <!-- etc. -->
</datalist>

The value of the list attribute in the input element (which could be any of the text-like input types) binds it to a datalist element with the corresponding ID (“country_name”, in this example). As a user types in the text field, if what they type matches the start of anything in the data list, those matches will be shown underneath the text field as suggestions. So, here, if “A” is typed, the 8 countries beginning with “a” are displayed. If “L” is typed after “A”, the list of suggestions will reduce to just “Albania” and “Algeria”, and so on. The data sent when the form is submitted will be whatever is in the text field – it could be something selected from the list or it could be something completely different, inputted by the user.

HTML5 Forms Pt. 1: Input Types

HTML5 greatly advances form controls, with numerous additional input types, several new attributes, and a handful of extra elements.

Additional input types

Basic form fields created using the input element include text, password, checkbox, radio, and submit, which have already been covered in the HTML Beginner section. These types have been extended in HTML5 to accommodate more specific fields:

Search

Used for a search query text box, this performs exactly as a standard text input should.


<input type="search" name="search">

Telephone, URL, and email addresses

Other “special” text input types include tel, for telephone numbers, url, for web addresses, and email, for email addresses.


<input type="tel" name="telephone_number">
<input type="url" name="web_address">
<input type="email" name="email_address">

Numbers and ranges

A simple text box that also allows a user to directly type in a number, or cycle through numbers (usually using an up and down arrow to the side of the field), can be achieved with type="number". A further step attribute can be added to specify how much is added or subtracted from the number with each increment.

If you also want the number to have a minimum or maximum value, you can further use the min and max attributes.


<input type="number" name="quantity" step="2" min="20" max="30">

Once again, if this is supported, the user will be able either to type directly into the field or, if using the arrows, cycle between 20 and 30, two units at a time.

An alternative to the digits-in-a-text-box approach can be achieved using type="range". By default, this should be displayed as a horizontal bar with a slider in the middle of it. The user can then adjust the slider left and right, the far left resulting in a value of “0” and the far right a value of “100”. This range can be adjusted using the min and max attributes.


<input type="range" name="temperature" min="15" max="25" step="0.5" value="18.5">

Dates and times

There are several input types for dates and times:

  • type="datetime"
  • type="date"
  • type="month"
  • type="week"
  • type="time"
  • type="datetime-local"

If supported (they aren’t, widely, and they are also inconsistent between browsers), these will prompt the user to enter a date or time in a specific format, either by directly typing it in, cycling through one week/day/hour/minute/etc. at a time, or by selecting from a dropdown calendar.

Color

Finally, type="color" is designed to allow a user to select a color, sending a six-digit hex code as its value.


<input name="color" type="color" value="#ff8800">

Accessible Forms

Labels

Each form field should have its own explicit label. The label tag sorts this out, with a for attribute that associates it to a form element:


<form>
    <label for="yourName">Your Name</label>
    <input name="yourName" id="yourName">
    <!-- etc. -->

Labels have the added bonus of visual browsers rendering the labels themselves clickable, putting the focus on the associated form field.

Field sets and legends

You can group fields, for example name (first, last, middle, title etc.) or address (line 1, line 2, county, country, postal code, country etc.) using the fieldset tag.

Within the field set, you can set a caption with the legend tag.


<form action="somescript.php" >
    <fieldset>
        <legend>Name</legend>
        <p>First name <input name="firstName"></p>
        <p>Last name <input name="lastName"></p>
    </fieldset>
    <fieldset>
        <legend>Address</legend>
        <p>Address <textarea name="address"></textarea></p>
        <p>Postal code <input name="postcode"></p>
    </fieldset>
    <!-- etc. -->

Option groups

The optgroup element groups options in a select box. It requires a label attribute, the value of which is displayed as a non-selectable pseudo-heading preceding that group in the drop-down list of visual browsers.


<select name="country">
    <optgroup label="Africa">
        <option value="gam">Gambia</option>
        <option value="mad">Madagascar</option>
        <option value="nam">Namibia</option>
    </optgroup>
    <optgroup label="Europe">
        <option value="fra">France</option>
        <option value="rus">Russia</option>
        <option value="uk">UK</option>
    </optgroup>
    <optgroup label="North America">
        <option value="can">Canada</option>
        <option value="mex">Mexico</option>
        <option value="usa">USA</option>
    </optgroup>
</select>

Navigating fields

Like links, form fields (and field sets) need to be navigated to without the use of a pointing device, such as a mouse. The same methods used in links to make this task easier can be used on form elements – tab stops and access keys.

The accesskey and tabindex attributes can be added to the individual form tags such as input and also to legend tags.


<input name="firstName" accesskey="f" tabindex="1">

For more about this, see the Accessible Links page.

Accessible Links

Tabbing

Users who do not or cannot use pointing devices can tab through links and, as such, links should be in a logical tabbing order. The tabindex attribute allows you to define this order although if the HTML is linear, as it should be, a logical tabbing order should automatically fall into place.


<ul>
    <li><a href="here.html" tabindex="1">Here</a></li>
    <li><a href="there.html" tabindex="3">There</a></li>
    <li><a href="limbo.html" tabindex="2">Limbo</a></li>
</ul>

In this example (which is used purely as a demonstration – it would be quite dumb, practically speaking), tabbing would jump from “Here” to “Limbo” to “There”.

Link titles

If you have a link that isn’t self-descriptive, or the link destination could benefit from being explained in more detail, you can add information to a link using the title attribute.


<p>I'm really bad at writing link text. <a href="inept.html" title="Why I'm rubbish at writing link text: An explanation and an apology.">Click here</a> to find out more.</p>

Accesskeys

Access keys allow easier navigation by assigning a keyboard shortcut to a link (which will usually gain focus when the user presses “Alt” or “Ctrl” + the access key).


<a href="somepage.html" accesskey="s">Some page</a>

Skipping HTML

To aid tabbing, you can supply links that allow users to jump over chunks of your web page. You might want to allow someone to jump over a plethora of navigation links, for example, so they can just read a page’s main content rather than cycle through all of the links:


<header>
    <h1>The Heading</h1>
    <a href="#content">Skip to content</a>
</header> 

<nav>
    <!--loads of navigation stuff -->
</nav>

<section id="content">
    <!--lovely content -->
</section>

Tables: Columns, Headers, and Footers

So you think you know how to make a table. Sure, you know the table, tr, td and th tags, you’ve even got the rowspan and colspan attributes in your pocket. You can make a really cute little plywood coffee table, but don’t you want to know how to make one of those polished solid wood, glass top dining tables that can take the weight of an oversized elephant?

You do? Oh joy.

The Columns Strike Back

Table rows tend to make table columns look rather stupid. They do all the work, as the table is built row by row, leaving the columns feeling quite rejected.

Luckily for those eager columns though, the colgroup and col tags have come to their rescue.

These tags allow you to define the table columns and style them as desired, which is particularly useful if you want certain columns aligned or colored differently, as, without this, you would need to target individual cells.


<table>
    <colgroup>
        <col>
        <col class="alternative">
        <col>
    </colgroup>
    <tr>
        <td>This</td>
        <td>That</td>
        <td>The other</td>
    </tr>
    <tr>
        <td>Ladybird</td>
        <td>Locust</td>
        <td>Lunch</td>
    </tr>
</table>

In this example the styles of the CSS class “alternative” will be applied to the second column, or the second cell in every row.

You can also use the span attribute in a similar way to rowspan and colspan. Using it with the colgroup tag will define the number of rows that the column group will belong to, for example <colgroup span="2"></colgroup> would group the first two columns. Using span in the col tag is usually more useful, and could, for example, be applied to the above example like this:


<table>
    <colgroup>
        <col>
        <col span="2" class="alternative">
    </colgroup>
<!-- and so on -->

This would apply “alternative” to the last two columns.

Caption interlude

A brief and easy accessibility consideration is to apply a caption to the table. The caption element defines the caption and should be used straight after the opening table tag.


<table>
    <caption>Locust mating habits</caption>
<!-- etc. -->

Headers and Footers

thead, tfoot and tbody allow you to separate the table into header, footer and body, which can be handy when dealing with larger tables.

Whereas thead needs to come first, tfoot can, in fact come before a tbody (and you can have more than one tbody, if it takes your fancy) although browsers will render the tfoot element at the bottom of the table.


<table>
    <thead>
        <tr>
            <td>Header 1</td>
            <td>Header 2</td>
            <td>Header 3</td>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <td>Footer 1</td>
            <td>Footer 2</td>
            <td>Footer 3</td>
        </tr>
    </tfoot>
    <tbody>
        <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
            <td>Cell 3</td>
        </tr>
        <!-- etc. -->
    </tbody>
</table>

Conditional Comments

Older versions of Internet Explorer are frequently either inept or naughty. Or both. But they are still popular so we don’t want to ignore them.

Conditional comments, which are nothing more than simple HTML comments that IE (up to version 9) happens to take a peep at, are used to throw a chunk of HTML at these browsers and only these browsers. Other well behaved, top-of-the-class browsers will simply see them as unremarkable comments and move along.

They have become a commonly used method of latching extra CSS to a document to plaster over holes in these browsers’ display capabilities. So, for example, you might add something like this inside your head element:


<link href="everything.css" rel="stylesheet">
<!--[if IE]><link href="stupidie.css" rel="stylesheet"><![endif]-->

Everything between <!--[if IE]> and <![endif]--> will be picked up by Internet Explorer. So this will bolt on a CSS file as normal, and then, only if the browser is Internet Explorer (in practice, this will be Internet Explorer version 9 and below), it will also apply an extra CSS file patch.

You can also target specific versions of Internet Explorer:

  • <!--[if IE 6>
  • <!--[if IE 7>
  • <!--[if IE 8>
  • <!--[if IE 9>

You can also target all versions that are greater or less than a certain number:

  • eg. <!--[if IE gt 6]>… for IE versions greater than 6
  • eg. <!--[if IE gte 8]>… for IE versions greater than or equal to than 8
  • eg. <!--[if IE lt 7]>… for IE versions less than 7
  • eg. <!--[if IE lte 7]>… for IE versions less than or equal to 7

There are actually more options than this which are largely totally unnecessary. Take a look at Microsoft’s own take on it if you really feel compelled to find out more.

Text: Time, Mark, and “Presentational”

Time

time is by far the chocolate ice cream sexiest sweet sugar lovely of these tags and is used to make dates and times super-semantically rich and mmm.

The text sandwiched in the middle of the opening and closing tag can be any format of date of time – the whole precise lot, or just one part, such as a day. It is made more helpful, however, by the datetime attribute, the value of which should be a machine-readable date and/or time.


<p>Written by Doctor Who on <time datetime="2052-11-21">Thursday 21st November 2052</time>.</p>

Valid datetime values can take the format of a year-month-day date (as above), of as a “fuzzy” date, such as “2052-11”, of a time, such as “09:30” (always using a 24-hour clock) or a combination, such as “2052-11-21 09:30”. This can also accommodate time zones and durations.

Mark

Text can be highlighted, as if with a marker pen, using mark:


<blockquote>
    <p>He wants to play with his <mark>Legos</mark></p>
</blockquote>

<p>The person being quoted is clearly American because, for some odd reason, they pluralise "Lego".</p>

Yes, this is a form of emphasis, literally speaking, but it won’t always be considered emphasis in the original meaning (for example, the person being quoted above isn’t emphasizing “Legos”, the commenter is), hence its inclusion.

Redefining the “presentational” tags

One of the slightly more The single most revolting “advance” in HTML 5 is its attempt to redefine the archaic presentational tags. Once popular, many moons ago, they just won’t go away no matter how over the hill they are. These tags are also known as “Cliff Richard tags”.

Some of the newly defined blighters are helpful, some are questionable, and some have new definitions crowbarred in that are, to say the least, tenuous.

  • hr, no longer “horizontal rule”, is a thematic break, between paragraphs, for example, like those found in many a chapter of many a book.
  • small, used for small print. Arguably a fair point, “small print” has taken on a meaning beyond “print that is small”.
  • s, no longer “strikethrough”, is for text that is no longer correct (eg, this is <s>presentational, not</s> meaningful). Hmm. OK. Maybe. del still seems fine to most normals, though.
  • u, no longer “underline”, is for text that is unarticulated. It’s also “useless” but bonus point for the abbreviation remaining intact.
  • i, no longer “italic”, is for text in an alternate voice or representing a different quality of text. So, like, differently emphasized, then (see note below).
  • b, no longer “bold”, stands for “text to which attention is being drawn without conveying importance or suggesting an alternative voice” (and even that’s paraphrasing). b also stands for “bollocks.”
  • sub and sup are still subscript and superscript and yet, at the same time, they’re somehow not presentational anymore.

Adding more specific meaning is welcome but even when helpful, these tags still aren’t ideal – they’re ugly. Messy. While we’re loving semantics, we’re supposed to be happy with the likes of hr when “H.R.” is a misnomer? Tempered happiness, maybe.

In case you haven’t picked up on the subtleties, we recommend you avoid these tags whenever possible. They serve to pollute and confuse more than clarify and em does the job perfectly more often than not.

Sectioning

While headings do a grand, perfectly valid, job in defining the start of a new section or sub-section in a document, there are a number of elements that can be exploited to establish a cleaner, clearer semantic structure.

Whereas div elements can be used to contain sections, used primarily as scaffolding on which to hang CSS, they don’t hold a great deal of meaning. Sectioning involves a handful of tags that can be used to define specific parts of a page, such as articles, headers, footers, and navigation.

Articles and Sections

An article element can be used to mark up a standalone section of content. This could be used just once, if you think of a blog post as an article, for example, or a number of times, if you imagine replicating a traditional newspaper page with numerous articles.

A section element represents a more general section and could be used to split up an article, or to represent chapters, for example.


<article>
    <section id="intro">
        <p>[An introduction]</p>
    </section>
    <section id="main_content">
        <p>[Content]</p>
    </section>
    <section id="related">
        <ul>
            <li><a href="that.html">That related article</a></li>
            <li><a href="this.html">This related artivle</a></li>
        </ul>
    </section>
</article>

While divs could be used to make these separations (or even if you didn’t need these separations for styling), this provides a much richer, more meaningful document.

Headers and Footers

header and footer provide further specialized, self-descriptive, sections:

Definition Lists

The HTML Beginner Tutorial looked at unordered lists and ordered lists, but, much like Peter Cushing’s Doctor Who, definition lists are quite often forgotten. This is maybe because they are much more specific than ordered and unordered lists and therefore less useful, generally, but where there is a list of terms and descriptions (such as a glossary), a definition list is your go-to-element.

dl gets the ball rolling, similar to the ul and ol elements, establishing the list. Rather than containing li elements, though, definition lists have dt elements, which are the definition terms, followed by dd elements, which are definition descriptions associated to the dt elements.

There doesn’t have to be one dt followed by one dd, there can be any number of either. For example, if there are a number of words that have the same meaning, there might be a number of dt’s followed by one dd. If you have one word that means various different things, there might be one dt followed by several dd’s.


<h1>Some random glossary thing</h1>
<dl>
    <dt>HTML</dt>
    <dd>Abbreviation for HyperText Markup Language - a language used to make web pages.</dd>

    <dt>Dog</dt>
    <dd>Any carnivorous animal belonging to the family Canidae.</dd>
    <dd>The domesticated sub-species of the family Canidae, Canis lupus familiaris.</dd>

    <dt>Moo juice</dt>
    <dt>Cat beer</dt>
    <dt>Milk</dt>
    <dd>A white liquid produced by cows and used for human consumption.</dd>
</dl>